<?php

use App\Models\Macro;
use App\Models\MacroAssignment;
use App\Models\Setting;
use App\Services\MacrosImportService;
use Illuminate\Foundation\Testing\RefreshDatabase;

uses(RefreshDatabase::class);

test('import creates new macros from file', function () {
    $service = app(MacrosImportService::class);
    $result = $service->import(base_path('tests/fixtures/macros-sample.bin'), 'macros.bin');

    expect($result->new)->toBeGreaterThanOrEqual(1);
    expect($result->updated)->toBe(0);
    expect(Macro::count())->toBeGreaterThanOrEqual(1);
});

test('import stores hex color on macros', function () {
    $service = app(MacrosImportService::class);
    $service->import(base_path('tests/fixtures/macros-sample.bin'), 'macros.bin');

    expect(Macro::whereNotNull('color')->where('color', 'like', '#%')->count())->toBeGreaterThanOrEqual(1);
});

test('import marks missing macros as hidden', function () {
    $existing = Macro::factory()->create(['uuid' => 'FAKE-FFFF-FFFF-FFFF-FFFFFFFFFFFF', 'hidden_at' => null]);

    $service = app(MacrosImportService::class);
    $result = $service->import(base_path('tests/fixtures/macros-sample.bin'), 'macros.bin');

    expect($existing->fresh()->isHidden())->toBeTrue();
    expect($result->disabled)->toBeGreaterThanOrEqual(1);
});

test('import re-enables previously hidden macros that appear in file', function () {
    $service = app(MacrosImportService::class);
    $result = $service->import(base_path('tests/fixtures/macros-sample.bin'), 'macros.bin');
    $firstMacro = Macro::first();
    $firstMacro->update(['hidden_at' => now()]);

    $result = $service->import(base_path('tests/fixtures/macros-sample.bin'), 'macros.bin');

    expect($result->reEnabled)->toBeGreaterThanOrEqual(1);
    expect($firstMacro->fresh()->isHidden())->toBeFalse();
});

test('import builds warnings for disabled macros with active assignments', function () {
    $service = app(MacrosImportService::class);
    $service->import(base_path('tests/fixtures/macros-sample.bin'), 'macros.bin');

    $hiddenMacro = Macro::factory()->create(['uuid' => 'WARN-FFFF-FFFF-FFFF-FFFFFFFFFFFF', 'hidden_at' => now()]);
    MacroAssignment::create(['part_type' => 'song', 'macro_id' => $hiddenMacro->id, 'position' => 'all_slides', 'order' => 0]);

    $result = $service->import(base_path('tests/fixtures/macros-sample.bin'), 'macros.bin');

    expect(count($result->warnings))->toBeGreaterThanOrEqual(1);
    $warning = collect($result->warnings)->firstWhere('macro_uuid', 'WARN-FFFF-FFFF-FFFF-FFFFFFFFFFFF');
    expect($warning)->not->toBeNull();
});

test('import stores last imported metadata in settings', function () {
    $service = app(MacrosImportService::class);
    $service->import(base_path('tests/fixtures/macros-sample.bin'), 'macros.bin');

    expect(Setting::get('macros_last_imported_at'))->not->toBeNull();
    expect(Setting::get('macros_last_imported_filename'))->toBe('macros.bin');
});
