<?php

namespace App\Console\Commands;

use App\Jobs\ImportEventsJob;
use App\Models\Source;
use Illuminate\Console\Command;

class ImportEventsCommand extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'events:import {--sync : Run synchronously without queue}';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Import events from all active sources';

    /**
     * Execute the console command.
     */
    public function handle()
    {
        $sources = Source::where('status', 'active')->get();

        if ($sources->isEmpty()) {
            $this->error('No active sources found. Please add a source first.');
            return Command::FAILURE;
        }

        $this->info("Found {$sources->count()} active source(s):");
        foreach ($sources as $source) {
            $this->line("  • {$source->name}");
        }

        $sync = $this->option('sync');

        if ($sync) {
            $this->info('Running import synchronously...');
            foreach ($sources as $source) {
                $this->line("Importing from: {$source->name}");
                ImportEventsJob::dispatchSync($source);
            }
            $this->info('Import completed successfully!');
        } else {
            $this->info('Dispatching import jobs to queue...');
            foreach ($sources as $source) {
                ImportEventsJob::dispatch($source);
                $this->line("Queued import for: {$source->name}");
            }
            $this->info('All import jobs have been queued!');
        }

        return Command::SUCCESS;
    }
}