<?php

namespace App\Services;

use App\Models\Song;
use App\Models\SongArrangement;
use App\Models\SongArrangementGroup;
use App\Models\SongGroup;
use Illuminate\Support\Facades\DB;

class SongService
{
    /**
     * Default-Gruppen für ein neues Lied erstellen.
     *
     * @return \Illuminate\Database\Eloquent\Collection<int, SongGroup>
     */
    public function createDefaultGroups(Song $song): \Illuminate\Database\Eloquent\Collection
    {
        $defaults = [
            ['name' => 'Strophe 1', 'color' => '#3B82F6', 'order' => 1],
            ['name' => 'Refrain', 'color' => '#10B981', 'order' => 2],
            ['name' => 'Bridge', 'color' => '#F59E0B', 'order' => 3],
        ];

        foreach ($defaults as $groupData) {
            $song->groups()->create($groupData);
        }

        return $song->groups()->orderBy('order')->get();
    }

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

        $groups = $song->groups()->orderBy('order')->get();

        foreach ($groups as $index => $group) {
            $arrangement->arrangementGroups()->create([
                'song_group_id' => $group->id,
                'order' => $index + 1,
            ]);
        }

        return $arrangement->load('arrangementGroups');
    }

    /**
     * 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->arrangementGroups()->orderBy('order')->get() as $group) {
                SongArrangementGroup::create([
                    'song_arrangement_id' => $clone->id,
                    'song_group_id' => $group->song_group_id,
                    'order' => $group->order,
                ]);
            }

            return $clone->load('arrangementGroups');
        });
    }
}
