<?php

namespace App\Services;

use App\Models\Label;
use App\Models\Song;
use App\Models\SongArrangement;
use App\Models\SongArrangementLabel;
use Illuminate\Support\Collection;
use Illuminate\Support\Facades\DB;

class SongService
{
    /**
     * Sicherstellen, dass die Default-Labels (Strophe 1, Refrain, Bridge) global existieren.
     *
     * @return Collection<int, Label>
     */
    public function createDefaultGroups(Song $song): Collection
    {
        $defaults = [
            ['name' => 'Strophe 1', 'color' => '#3B82F6'],
            ['name' => 'Refrain', 'color' => '#10B981'],
            ['name' => 'Bridge', 'color' => '#F59E0B'],
        ];

        $labels = collect();

        foreach ($defaults as $data) {
            $existing = Label::whereRaw('LOWER(name) = ?', [strtolower($data['name'])])->first();

            if ($existing === null) {
                $existing = Label::create([
                    'name' => $data['name'],
                    'color' => $data['color'],
                ]);
            }

            $labels->push($existing);
        }

        return $labels;
    }

    /**
     * Standard "Normal"-Arrangement mit den Default-Labels erstellen.
     */
    public function createDefaultArrangement(Song $song): SongArrangement
    {
        $arrangement = $song->arrangements()->create([
            'name' => 'Normal',
            'is_default' => true,
        ]);

        $labels = $this->createDefaultGroups($song);

        foreach ($labels->values() as $index => $label) {
            $arrangement->arrangementLabels()->create([
                'label_id' => $label->id,
                'order' => $index + 1,
            ]);
        }

        return $arrangement->load('arrangementLabels.label');
    }

    /**
     * Arrangement duplizieren mit neuem Namen.
     */
    public function duplicateArrangement(SongArrangement $arrangement, string $name): SongArrangement
    {
        return DB::transaction(function () use ($arrangement, $name) {
            $clone = $arrangement->replicate(['id', 'created_at', 'updated_at']);
            $clone->name = $name;
            $clone->is_default = false;
            $clone->save();

            foreach ($arrangement->arrangementLabels()->orderBy('order')->get() as $arrangementLabel) {
                SongArrangementLabel::create([
                    'song_arrangement_id' => $clone->id,
                    'label_id' => $arrangementLabel->label_id,
                    'order' => $arrangementLabel->order,
                ]);
            }

            return $clone->load('arrangementLabels.label');
        });
    }
}
