<?php

namespace App\Console\Commands;

use App\Models\Tenant;
use App\Services\RenewalService;
use Illuminate\Console\Command;

class ScanRenewalOpportunities extends Command
{
    protected $signature = 'renewals:scan {--tenant=} {--window=90}';

    protected $description = 'Create idempotent renewal opportunities from tenant expiry sources and dispatch due reminders.';

    public function handle(RenewalService $renewals): int
    {
        $query = Tenant::query()->whereNotIn('status', ['cancelled', 'suspended', 'archived']);
        if ($tenantId = $this->option('tenant')) {
            $query->whereKey($tenantId);
        }

        $created = 0;
        $reminders = 0;

        $query->chunkById(50, function ($tenants) use ($renewals, &$created, &$reminders) {
            foreach ($tenants as $tenant) {
                $created += $renewals->scanTenant($tenant, max(1, (int) $this->option('window')));
                $reminders += $renewals->dispatchDueReminders($tenant);
            }
        });

        $this->info("Renewal scan completed: {$created} opportunities created, {$reminders} reminders queued or delivered.");

        return self::SUCCESS;
    }
}
