<?php

namespace App\Console\Commands;

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

class ExpireLoyaltyPoints extends Command
{
    protected $signature = 'loyalty:expire-points';

    protected $description = 'Expire loyalty points past their validity date, for every tenant';

    public function handle(LoyaltyService $loyalty, CurrentContext $context): int
    {
        // Tenant-scoped sweep (see docs/migration-plan.md §1): loyalty ledgers
        // are tenant tables, so unlike the batches sweep this must bind each
        // tenant explicitly rather than running unscoped.
        $total = 0;

        foreach (Tenant::all() as $tenant) {
            $count = $context->runForTenant($tenant, fn () => $loyalty->expireDue());

            if ($count > 0) {
                AuditLog::record('loyalty.expired_auto', null, [
                    'count' => $count,
                    'description' => "Expired {$count} loyalty point batch(es) past their validity date.",
                ]);
            }

            $total += $count;
        }

        $this->info("Expired {$total} loyalty point batch(es) across all tenants.");

        return self::SUCCESS;
    }
}
