<?php

use App\Models\Service;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Schema;

test('service_macro_overrides table has expected columns', function () {
    expect(Schema::hasTable('service_macro_overrides'))->toBeTrue();
    expect(Schema::hasColumns('service_macro_overrides', ['id', 'service_id', 'part_type', 'created_at', 'updated_at']))->toBeTrue();
});

test('service_macro_assignments table has expected columns', function () {
    expect(Schema::hasTable('service_macro_assignments'))->toBeTrue();
    expect(Schema::hasColumns('service_macro_assignments', ['id', 'service_id', 'part_type', 'macro_id', 'position', 'label_id', 'order', 'created_at', 'updated_at']))->toBeTrue();
});

test('service_macro_overrides unique constraint on service_id and part_type', function () {
    $service = Service::factory()->create();
    DB::table('service_macro_overrides')->insert(['service_id' => $service->id, 'part_type' => 'song', 'created_at' => now(), 'updated_at' => now()]);

    expect(fn () => DB::table('service_macro_overrides')->insert(['service_id' => $service->id, 'part_type' => 'song', 'created_at' => now(), 'updated_at' => now()]))
        ->toThrow(\Exception::class);
});

test('service delete cascades to overrides and assignments', function () {
    $service = Service::factory()->create();
    $macroId = DB::table('macros')->insertGetId(['uuid' => 'CCDD-1111-2222-3333-FFFFFFFFFFFF', 'name' => 'Test', 'created_at' => now(), 'updated_at' => now()]);
    DB::table('service_macro_overrides')->insert(['service_id' => $service->id, 'part_type' => 'sermon', 'created_at' => now(), 'updated_at' => now()]);
    DB::table('service_macro_assignments')->insert(['service_id' => $service->id, 'part_type' => 'sermon', 'macro_id' => $macroId, 'position' => 'all_slides', 'order' => 0, 'created_at' => now(), 'updated_at' => now()]);

    $service->delete();

    expect(DB::table('service_macro_overrides')->where('service_id', $service->id)->count())->toBe(0);
    expect(DB::table('service_macro_assignments')->where('service_id', $service->id)->count())->toBe(0);
});
