<?php

namespace App\Console\Commands;

use App\Models\MeetupEvent;
use App\Models\MexcoEventLicense;
use App\Models\MexcoPlan;
use App\Services\EntitlementService;
use App\Services\UsageService;
use Illuminate\Console\Command;

class MexcoBackfillLicenses extends Command
{
    protected $signature = 'mexco:backfill-licenses {--plan=pro : Default plan code for events without a license}';

    protected $description = 'Create event licenses, usage records, and entitlements for existing meetup events';

    public function handle(EntitlementService $entitlements, UsageService $usage): int
    {
        $planCode = (string) $this->option('plan');
        $plan = MexcoPlan::query()->where('code', $planCode)->first();

        if (! $plan) {
            $this->error("Plan [{$planCode}] not found. Run MexcoCatalogSeeder first.");

            return self::FAILURE;
        }

        $events = MeetupEvent::query()->orderBy('id')->get();
        $created = 0;
        $rebuilt = 0;

        foreach ($events as $event) {
            $license = MexcoEventLicense::query()->where('event_id', $event->id)->first();

            if (! $license) {
                $entitlements->ensureLicense($event, $planCode);
                $created++;
                $this->line("Created license for [{$event->id}] on plan {$planCode}");
            }

            $usage->recalculate($event->id);
            $entitlements->rebuildEntitlements($event->id);
            $rebuilt++;
        }

        $this->info("Done. Licenses created: {$created}. Entitlements rebuilt: {$rebuilt}.");

        return self::SUCCESS;
    }
}
