<?php

namespace App\Console\Commands;

use App\Services\AuditLog;
use App\Services\BatchService;
use App\Services\CurrentContext;
use Illuminate\Console\Command;

class FlagExpiredBatches extends Command
{
    protected $signature = 'batches:flag-expired';

    protected $description = 'Mark stock batches whose expiry_date < today as expired';

    public function handle(BatchService $batches, CurrentContext $context): int
    {
        // Deliberate cross-tenant sweep: expire batches for every tenant in one
        // pass (see docs/migration-plan.md §1 — TenantScope now requires this
        // explicit opt-in instead of silently passing through in console).
        $count = $context->runWithoutTenant(fn () => $batches->flagExpiredBatches());

        AuditLog::record('batches.flagged_expired', null, [
            'count' => $count,
            'description' => "Flagged {$count} batch(es) as expired.",
        ]);

        $this->info("Flagged {$count} batch(es) as expired.");

        return self::SUCCESS;
    }
}
