<?php

namespace App\Console\Commands;

use App\Models\Service;
use App\Services\ChurchToolsService;
use Illuminate\Console\Command;
use Illuminate\Support\Carbon;
use Illuminate\Support\Str;
use Throwable;

class DiscoverAgendaTypes extends Command
{
    protected $signature = 'cts:discover-agenda-types';

    protected $description = 'Zeigt alle Agenda-Item-Typen eines Services an (Diagnose)';

    public function handle(ChurchToolsService $churchToolsService): int
    {
        try {
            $service = Service::where('date', '>=', Carbon::today())
                ->orderBy('date')
                ->first();

            if (! $service) {
                $this->info('Kein bevorstehender Service gefunden.');

                return self::SUCCESS;
            }

            $ctsEventId = (int) $service->cts_event_id;
            $agenda = $churchToolsService->syncAgenda($ctsEventId);

            if (! $agenda) {
                $this->info('Keine Agenda für diesen Service gefunden.');

                return self::SUCCESS;
            }

            $items = $agenda->getItems();

            if (empty($items)) {
                $this->info('Keine Agenda-Items gefunden.');

                return self::SUCCESS;
            }

            $headers = ['Position', 'Titel', 'Typ', 'Hat Song', 'Vor Event', 'Dauer'];
            $rows = [];
            $types = [];

            foreach ($items as $item) {
                $position = $item->getPosition() ?? '-';
                $title = Str::limit($item->getTitle() ?? '', 40, '...');
                $type = $item->getType() ?? '-';
                $hasSong = $item->getSong() !== null ? 'Ja' : 'Nein';
                $isBeforeEvent = $item->getIsBeforeEvent() ? 'Ja' : 'Nein';
                $duration = $item->getDuration() ?? '-';

                $rows[] = [
                    $position,
                    $title,
                    $type,
                    $hasSong,
                    $isBeforeEvent,
                    $duration,
                ];

                if ($type !== '-' && ! in_array($type, $types)) {
                    $types[] = $type;
                }
            }

            $this->table($headers, $rows);
            $this->newLine();
            $this->info('Unique Types:');
            foreach ($types as $type) {
                $this->line('  - '.$type);
            }

            return self::SUCCESS;
        } catch (Throwable $exception) {
            $this->error('Fehler beim Abrufen der Agenda: '.$exception->getMessage());

            return self::FAILURE;
        }
    }
}
