<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Support\Facades\DB;

return new class extends Migration
{
    public function up(): void
    {
        $name = DB::table('settings')->where('key', 'macro_name')->value('value');
        $uuid = DB::table('settings')->where('key', 'macro_uuid')->value('value');

        if (empty($name) || empty($uuid)) {
            return;
        }

        $collectionName = DB::table('settings')->where('key', 'macro_collection_name')->value('value');
        $collectionUuid = DB::table('settings')->where('key', 'macro_collection_uuid')->value('value');

        DB::transaction(function () use ($name, $uuid, $collectionName, $collectionUuid) {
            $labelId = DB::table('labels')->insertGetId([
                'name' => 'Copyright',
                'color' => null,
                'created_at' => now(),
                'updated_at' => now(),
            ]);

            $macroId = DB::table('macros')->insertGetId([
                'uuid' => strtoupper($uuid),
                'name' => $name,
                'last_imported_filename' => 'legacy-settings-migration',
                'last_imported_at' => now(),
                'created_at' => now(),
                'updated_at' => now(),
            ]);

            if (! empty($collectionUuid) && ! empty($collectionName)) {
                $collectionId = DB::table('macro_collections')->insertGetId([
                    'uuid' => strtoupper($collectionUuid),
                    'name' => $collectionName,
                    'last_imported_at' => now(),
                    'created_at' => now(),
                    'updated_at' => now(),
                ]);
                DB::table('macro_collection_macros')->insert([
                    'macro_collection_id' => $collectionId,
                    'macro_id' => $macroId,
                    'order' => 0,
                    'created_at' => now(),
                    'updated_at' => now(),
                ]);
            }

            DB::table('macro_assignments')->insert([
                'part_type' => 'song',
                'macro_id' => $macroId,
                'position' => 'by_label',
                'label_id' => $labelId,
                'order' => 0,
                'created_at' => now(),
                'updated_at' => now(),
            ]);

            DB::table('settings')
                ->whereIn('key', ['macro_name', 'macro_uuid', 'macro_collection_name', 'macro_collection_uuid'])
                ->delete();
        });
    }

    public function down(): void {}
};
