<?php

namespace App\Console\Commands;

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

class EvaluateLoyaltyTiers extends Command
{
    protected $signature = 'loyalty:evaluate-tiers';

    protected $description = 'Re-evaluate every customer loyalty tier against lifetime points, for every tenant';

    public function handle(LoyaltyService $loyalty, CurrentContext $context): int
    {
        // Tenant-scoped sweep (see docs/migration-plan.md §1): same explicit
        // per-tenant binding as loyalty:expire-points — re-evaluation is
        // normally triggered automatically on earn/redeem/adjust, this is the
        // reconciliation pass for manual corrections or tier threshold edits.
        $total = 0;

        foreach (Tenant::all() as $tenant) {
            $processed = $context->runForTenant($tenant, function () use ($loyalty): int {
                $count = 0;

                CustomerLoyaltyBalance::query()
                    ->whereNotNull('tier_id')
                    ->orWhere('lifetime_points', '>', 0)
                    ->lazy()
                    ->each(function (CustomerLoyaltyBalance $balance) use ($loyalty, &$count): void {
                        $loyalty->evaluateTier($balance->fresh());
                        $count++;
                    });

                return $count;
            });

            $total += $processed;
        }

        $this->info("Re-evaluated loyalty tiers for {$total} customer balance(s) across all tenants.");

        return self::SUCCESS;
    }
}
