<?php

namespace App\Console\Commands;

use App\Models\Central\Tenant;
use App\Services\Storage\TenantStorage;
use Illuminate\Console\Command;

/**
 * Recomputes each tenant's cached storage usage (bytes + file count) by listing
 * its prefix on the platform bucket, so Master Control → Tenants never lists
 * objects against R2 per request. Run on a schedule or via that page's
 * "Recalculate storage" button.
 */
class RecalculateStorageUsage extends Command
{
    protected $signature = 'storage:recalculate-usage {--tenant= : Only recalculate a single tenant id}';

    protected $description = 'Recalculate cached storage usage for tenants';

    public function handle(TenantStorage $storage): int
    {
        $query = Tenant::query();
        if ($id = $this->option('tenant')) {
            $query->whereKey($id);
        }

        $tenants = $query->get();
        $this->info("Recalculating storage usage for {$tenants->count()} tenant(s)…");

        foreach ($tenants as $tenant) {
            try {
                $usage = $storage->usage($tenant);
                $tenant->update([
                    'storage_used_bytes' => $usage['bytes'],
                    'storage_files_count' => $usage['files'],
                    'storage_calculated_at' => now(),
                ]);
                $this->line("  {$tenant->name}: {$usage['files']} files, {$usage['bytes']} bytes");
            } catch (\Throwable $e) {
                $this->warn("  {$tenant->name}: failed — {$e->getMessage()}");
            }
        }

        $this->info('Done.');

        return self::SUCCESS;
    }
}
