<?php

namespace App\Console\Commands;

use App\Models\Central\Tenant;
use App\Services\CurrentContext;
use App\Services\DocumentNumberService;
use Illuminate\Console\Command;

/**
 * Resolved per docs/migration-plan.md Decisions Log #4: the source app's
 * command called DocumentNumberService::resync() with no tenant context at
 * all, relying on the pre-hardening TenantScope silently passing CLI queries
 * through unscoped. That was already a latent bug once multi-tenancy landed
 * — `document_sequences.sequence_key` (and `invoices.invoice_number` etc.)
 * are tenant-scoped via a composite unique key (see
 * 2026_07_08_000002_add_tenant_id_to_owned_tables.php), so two tenants can
 * legitimately share the same sequence_key (e.g. both have "invoice:2026")
 * and an unscoped resync would blend their highest-issued numbers together —
 * a real correctness bug, not a benign filter mismatch. The new fail-loud
 * TenantScope just turned that silent corruption into a loud crash instead
 * of quietly happening; this fixes the actual gap by resyncing every active
 * tenant independently, each correctly scoped via runForTenant() (the same
 * idiom TenantProvisioner/ImpersonationController already use elsewhere in
 * this codebase for cross-tenant admin operations).
 */
class ResyncDocumentSequences extends Command
{
    protected $signature = 'documents:resync-sequences';

    protected $description = 'Advance document number counters to match the highest issued document, repairing drift from seeded or imported data.';

    public function handle(DocumentNumberService $numbers, CurrentContext $context): int
    {
        $tenants = Tenant::active()->get();

        if ($tenants->isEmpty()) {
            $this->info('No active tenants to resync.');

            return self::SUCCESS;
        }

        $totalChanged = 0;

        foreach ($tenants as $tenant) {
            $changed = $context->runForTenant($tenant, fn () => $numbers->resync());

            if ($changed === []) {
                continue;
            }

            $this->line("Tenant [{$tenant->slug}]:");
            foreach ($changed as $key => $value) {
                $this->line("  {$key} → next_value {$value}");
            }
            $totalChanged += count($changed);
        }

        if ($totalChanged === 0) {
            $this->info('All document sequences already in sync across all tenants.');

            return self::SUCCESS;
        }

        $this->info("{$totalChanged} sequence(s) resynced across ".$tenants->count().' tenant(s).');

        return self::SUCCESS;
    }
}
