<?php

use Illuminate\Support\Facades\DB;

test('migration is no-op when macro settings are empty', function () {
    expect(DB::table('macro_assignments')->count())->toBe(0);
    expect(DB::table('macros')->count())->toBe(0);
});

test('migration creates assignment when all 4 keys are present', function () {
    DB::table('settings')->insert([
        ['key' => 'macro_name', 'value' => 'Copyright Makro', 'created_at' => now(), 'updated_at' => now()],
        ['key' => 'macro_uuid', 'value' => 'AAAAAAAA-1111-2222-3333-FFFFFFFFFFFF', 'created_at' => now(), 'updated_at' => now()],
        ['key' => 'macro_collection_name', 'value' => '--MAIN--', 'created_at' => now(), 'updated_at' => now()],
        ['key' => 'macro_collection_uuid', 'value' => '8D02FC57-83F8-4042-9B90-81C229728426', 'created_at' => now(), 'updated_at' => now()],
    ]);

    $migration = require database_path('migrations/2026_05_03_100700_migrate_legacy_macro_settings.php');
    $migration->up();

    expect(DB::table('labels')->where('name', 'Copyright')->exists())->toBeTrue();
    expect(DB::table('macros')->where('uuid', 'AAAAAAAA-1111-2222-3333-FFFFFFFFFFFF')->exists())->toBeTrue();
    expect(DB::table('macro_assignments')->where('part_type', 'song')->where('position', 'by_label')->exists())->toBeTrue();
    expect(DB::table('settings')->whereIn('key', ['macro_name', 'macro_uuid', 'macro_collection_name', 'macro_collection_uuid'])->count())->toBe(0);
});

test('migration works when only name and uuid are set (no collection)', function () {
    DB::table('settings')->insert([
        ['key' => 'macro_name', 'value' => 'Simple Makro', 'created_at' => now(), 'updated_at' => now()],
        ['key' => 'macro_uuid', 'value' => 'BBBBBBBB-1111-2222-3333-FFFFFFFFFFFF', 'created_at' => now(), 'updated_at' => now()],
    ]);

    $migration = require database_path('migrations/2026_05_03_100700_migrate_legacy_macro_settings.php');
    $migration->up();

    expect(DB::table('macro_assignments')->where('part_type', 'song')->exists())->toBeTrue();
    expect(DB::table('macro_collections')->count())->toBe(0);
});

test('migration is no-op when macro_uuid is empty', function () {
    DB::table('settings')->insert([
        ['key' => 'macro_name', 'value' => 'Makro Ohne UUID', 'created_at' => now(), 'updated_at' => now()],
        ['key' => 'macro_uuid', 'value' => '', 'created_at' => now(), 'updated_at' => now()],
    ]);

    $migration = require database_path('migrations/2026_05_03_100700_migrate_legacy_macro_settings.php');
    $migration->up();

    expect(DB::table('macro_assignments')->count())->toBe(0);
});
