<?php

namespace App\Console\Commands;

use App\Models\EventPhotoboothSetting;
use App\Services\Photobooth\PhotoboothIngestService;
use Illuminate\Console\Command;

class PhotoboothIngestCommand extends Command
{
    protected $signature = 'photobooth:ingest {--event= : Restrict ingestion to a single event ID}
        {--max-files= : Maximum files to import per event in this run}';

    protected $description = 'Ingest pending Photobooth uploads from the FTP mount into event storage.';

    public function handle(PhotoboothIngestService $ingestService): int
    {
        $eventId = $this->option('event');
        $maxFiles = $this->option('max-files');
        $processedTotal = 0;
        $skippedTotal = 0;

        $query = EventPhotoboothSetting::query()
            ->where('enabled', true)
            ->whereNotNull('path')
            ->with('event');

        if ($eventId) {
            $query->where('event_id', $eventId);
        }

        $query->chunkById(25, function ($settings) use ($ingestService, $maxFiles, &$processedTotal, &$skippedTotal) {
            foreach ($settings as $setting) {
                $event = $setting->event;

                if (! $event) {
                    continue;
                }

                $summary = $ingestService->ingest($event, $maxFiles ? (int) $maxFiles : null);
                $processedTotal += $summary['processed'] ?? 0;
                $skippedTotal += $summary['skipped'] ?? 0;

                $this->line(sprintf(
                    'Event #%d (%s): %d imported, %d skipped',
                    $event->id,
                    $event->slug ?? 'event',
                    $summary['processed'] ?? 0,
                    $summary['skipped'] ?? 0
                ));
            }
        });

        $this->info(sprintf('Photobooth ingest finished. Processed: %d, Skipped: %d', $processedTotal, $skippedTotal));

        return self::SUCCESS;
    }
}
