<?php

namespace App\Console\Commands;

use App\Models\MexcoEventLicense;
use App\Models\MeetupEvent;
use App\Services\BillingService;
use Illuminate\Console\Command;

class MexcoBackfillInvoices extends Command
{
    protected $signature = 'mexco:backfill-invoices';

    protected $description = 'Create draft invoices for existing paid event licenses without billing records';

    public function handle(BillingService $billing): int
    {
        $licenses = MexcoEventLicense::query()
            ->with(['plan', 'eventAddons.addon', 'event'])
            ->where('is_campus_sponsored', false)
            ->where('price_cents', '>', 0)
            ->get();

        $created = 0;
        $skipped = 0;

        foreach ($licenses as $license) {
            $event = $license->event ?? MeetupEvent::query()->find($license->event_id);
            if (! $event || ! $event->organisation_id) {
                $skipped++;

                continue;
            }

            $invoice = $billing->createDraftInvoiceForLicense($event, $license);
            if ($invoice && $invoice->wasRecentlyCreated) {
                $created++;
                $this->line("Created invoice {$invoice->invoice_number} for [{$event->id}]");
            } else {
                $skipped++;
            }
        }

        $this->info("Done. Invoices created: {$created}. Skipped: {$skipped}.");

        return self::SUCCESS;
    }
}
