<?php

namespace App\Console\Commands;

use App\Services\ChurchToolsService;
use CTApi\Exceptions\CTConnectException;
use CTApi\Exceptions\CTPermissionException;
use CTApi\Exceptions\CTRequestException;
use Illuminate\Console\Command;
use Throwable;

class SyncChurchToolsCommand extends Command
{
    protected $signature = 'cts:sync';

    protected $description = 'Synchronisiert Gottesdienste und Songs aus ChurchTools';

    public function handle(ChurchToolsService $churchToolsService): int
    {
        try {
            $summary = $churchToolsService->sync();

            $this->info('Daten wurden aktualisiert');
            $this->line('Services: '.$summary['services_count']);
            $this->line('Songs in Agenda: '.$summary['songs_count']);
            $this->line('Gematchte Songs: '.$summary['matched_songs_count']);
            $this->line('Nicht gematchte Songs: '.$summary['unmatched_songs_count']);

            return self::SUCCESS;
        } catch (CTPermissionException $e) {
            $this->error('Authentifizierungsfehler: API-Token ungueltig oder abgelaufen.');
            $this->error('Bitte pruefe CTS_API_TOKEN in der .env Datei.');
            $this->line('  Details: '.$e->getMessage());

            if ($this->getOutput()->isVerbose()) {
                $this->line('  Exception: '.$e::class);
                $this->line('  Trace: '.$e->getTraceAsString());
            }

            return self::FAILURE;
        } catch (CTConnectException $e) {
            $this->error('Verbindungsfehler: ChurchTools Server nicht erreichbar.');
            $this->error('Bitte pruefe CTS_API_URL in der .env Datei und die Netzwerkverbindung.');
            $this->line('  Details: '.$e->getMessage());

            if ($this->getOutput()->isVerbose()) {
                $this->line('  Exception: '.$e::class);
                $this->line('  Trace: '.$e->getTraceAsString());
            }

            return self::FAILURE;
        } catch (CTRequestException $e) {
            $this->error('API-Fehler: '.$e->getMessage());
            $this->line('  Exception: '.$e::class);

            if ($this->getOutput()->isVerbose()) {
                $this->line('  Trace: '.$e->getTraceAsString());
            }

            return self::FAILURE;
        } catch (Throwable $e) {
            $this->error('Fehler beim Synchronisieren: '.$e->getMessage());
            $this->line('  Exception: '.$e::class);

            if ($this->getOutput()->isVerbose()) {
                $this->line('  Trace: '.$e->getTraceAsString());
            }

            return self::FAILURE;
        }
    }
}
