<?php

namespace App\Console\Commands;

use App\Models\Event;
use App\Services\EventJoinTokenService;
use Illuminate\Console\Command;

class BackfillEventInvitations extends Command
{
    protected $signature = 'tenant:backfill-invitations {--tenant=} {--limit=100} {--dry-run}';

    protected $description = 'Ensure every event has at least one invitation link (join token).';

    public function handle(EventJoinTokenService $joinTokenService): int
    {
        $tenantId = $this->option('tenant');
        $limit = (int) $this->option('limit');
        $dryRun = (bool) $this->option('dry-run');

        $query = Event::query()
            ->doesntHave('joinTokens')
            ->orderBy('id');

        if ($tenantId) {
            $query->where('tenant_id', $tenantId);
        }

        $processed = 0;

        $query->chunkById(50, function ($events) use ($joinTokenService, $dryRun, &$processed, $limit) {
            foreach ($events as $event) {
                if ($processed >= $limit) {
                    return false;
                }

                $processed++;

                if ($dryRun) {
                    $this->line("[dry-run] Would create invitation for event #{$event->id} ({$event->slug})");

                    continue;
                }

                $joinTokenService->createToken($event, [
                    'label' => 'Standard-Link',
                    'metadata' => [
                        'auto_generated' => true,
                        'backfilled_at' => now()->toIso8601String(),
                    ],
                ]);

                $this->line("Created invitation for event #{$event->id} ({$event->slug})");
            }

            return true;
        });

        if ($processed === 0) {
            $this->info('No events required backfilling.');
        } else {
            $suffix = $dryRun ? ' (dry-run)' : '';
            $this->info("Processed {$processed} event(s){$suffix}.");
        }

        return self::SUCCESS;
    }
}
