<?php

namespace App\Console\Commands;

use App\Models\Commons\File;
use App\Models\Folder;
use App\Models\Tenants\Tenant;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\DB;

class RecordStorageUsage extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'storage:record-usage';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Record daily storage usage history for all active tenants';

    /**
     * Execute the console command.
     */
    public function handle(): int
    {
        $tenants = Tenant::active()->get();

        $recorded = 0;
        foreach ($tenants as $tenant) {
            try {
                // Calculate folder usage
                $folderUsage = File::where('tenant_id', $tenant->id)
                    ->whereNull('deleted_at')
                    ->whereNotNull('folder_id')
                    ->selectRaw('folder_id, SUM(file_size) as total')
                    ->groupBy('folder_id')
                    ->get()
                    ->mapWithKeys(function ($item) {
                        $folder = Folder::find($item->folder_id);
                        if ($folder) {
                            return [$folder->folder_key => (int) $item->total];
                        }

                        return [];
                    });

                // Count active files
                $fileCount = File::where('tenant_id', $tenant->id)
                    ->whereNull('deleted_at')
                    ->count();

                // Insert history record
                DB::table('storage_usage_history')->insert([
                    'tenant_id' => $tenant->id,
                    'storage_used' => $tenant->storage_used,
                    'file_count' => $fileCount,
                    'folder_usage' => json_encode($folderUsage),
                    'recorded_at' => now(),
                ]);

                $recorded++;
            } catch (\Exception $e) {
                $this->error("Failed to record usage for tenant {$tenant->id}: {$e->getMessage()}");
            }
        }

        $this->info("Storage usage recorded for {$recorded}/{$tenants->count()} tenants");

        return Command::SUCCESS;
    }
}
