<?php

namespace App\Services;

use App\Exceptions\DuplicateCcliSongException;
use App\Models\ApiRequestLog;
use App\Models\Label;
use App\Models\Setting;
use App\Models\Song;
use App\Models\SongArrangement;
use App\Models\SongArrangementLabel;
use App\Models\SongSlide;
use App\Services\DTO\ParsedCcliSection;
use App\Services\DTO\ParsedCcliSong;
use App\Support\CcliLabels;
use Illuminate\Support\Facades\DB;
use RuntimeException;

final class CcliImportService
{
    private const DEFAULT_LABEL_COLOR = '#3B82F6';

    public function __construct(
        private readonly CcliPasteParser $parser,
    ) {}

    /** @return array{song: Song, status: 'created'|'restored', warnings: string[]} */
    public function import(string $rawText, ?string $sourceUrl = null): array
    {
        $startedAt = microtime(true);
        $parsed = $this->parser->parse($rawText);

        if ($parsed->ccliId === null || trim($parsed->ccliId) === '') {
            throw new RuntimeException('Keine CCLI-Nummer gefunden — bitte vollständige SongSelect-Liedseite einfügen.');
        }

        $song = Song::withTrashed()->where('ccli_id', $parsed->ccliId)->first();
        $status = 'created';

        if ($song !== null && ! $song->trashed()) {
            throw new DuplicateCcliSongException($song->id);
        }

        if ($song !== null) {
            $status = 'restored';
        }

        return DB::transaction(function () use ($parsed, $sourceUrl, $song, $status, $startedAt): array {
            if ($song !== null && $song->trashed()) {
                $song->restore();
            }

            $song = $this->upsertSong($parsed, $sourceUrl, $song);
            $warnings = [];

            $translationLanguage = Setting::get('default_translation_language', 'DE');
            if ($translationLanguage === null || trim($translationLanguage) === '') {
                $warnings[] = 'Keine Standard-Übersetzungssprache gesetzt, DE wird verwendet.';
            }

            $labelIds = [];
            $hasTranslation = false;

            foreach ($parsed->sections as $section) {
                $label = $this->resolveLabel($section);
                $labelIds[] = $label->id;

                $label->songSlides()->delete();

                foreach ($section->lines as $order => $line) {
                    $translatedLine = $section->linesTranslated[$order] ?? null;
                    $hasTranslation = $hasTranslation || ($translatedLine !== null && trim($translatedLine) !== '');

                    SongSlide::create([
                        'label_id' => $label->id,
                        'order' => $order + 1,
                        'text_content' => $line,
                        'text_content_translated' => $translatedLine,
                    ]);
                }
            }

            $song->update([
                'has_translation' => $hasTranslation,
                'imported_from_ccli_at' => now(),
                'ccli_source_url' => $sourceUrl ?? $parsed->sourceUrl,
            ]);

            $arrangement = SongArrangement::updateOrCreate(
                ['song_id' => $song->id, 'name' => 'normal'],
                ['is_default' => true],
            );

            SongArrangementLabel::where('song_arrangement_id', $arrangement->id)->delete();

            foreach ($labelIds as $order => $labelId) {
                SongArrangementLabel::create([
                    'song_arrangement_id' => $arrangement->id,
                    'label_id' => $labelId,
                    'order' => $order + 1,
                ]);
            }

            $song = $song->fresh(['arrangements.arrangementLabels.label.songSlides']);

            ApiRequestLog::create([
                'method' => 'import',
                'endpoint' => 'paste',
                'status' => 'success',
                'request_context' => ['ccli_id' => $parsed->ccliId, 'mode' => $status],
                'response_summary' => "Song {$status}: {$song->title}",
                'response_body' => null,
                'duration_ms' => (int) round((microtime(true) - $startedAt) * 1000),
            ]);

            return ['song' => $song, 'status' => $status, 'warnings' => $warnings];
        });
    }

    private function upsertSong(ParsedCcliSong $parsed, ?string $sourceUrl, ?Song $song): Song
    {
        $songData = [
            'title' => $parsed->title,
            'author' => $parsed->author,
            'copyright_text' => $parsed->copyrightText,
            'copyright_year' => $parsed->year,
            'publisher' => $parsed->copyrightText,
            'ccli_source_url' => $sourceUrl ?? $parsed->sourceUrl,
        ];

        if ($song !== null) {
            $song->update($songData);

            return $song;
        }

        return Song::create(array_merge($songData, ['ccli_id' => $parsed->ccliId]));
    }

    private function resolveLabel(ParsedCcliSection $section): Label
    {
        $canonicalLabelName = CcliLabels::normalizeLabelName(
            $section->kind.($section->number ? ' '.$section->number : ''),
        );

        return Label::firstOrCreate(
            ['name' => $canonicalLabelName],
            ['color' => self::DEFAULT_LABEL_COLOR, 'last_imported_at' => now()],
        );
    }
}
