<?php

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

return new class extends Migration
{
    public function up(): void
    {
        Schema::table('trainers', function (Blueprint $table) {
            // Drop the existing unique constraint and FK on employee_id
            $table->dropUnique(['employee_id']);
            $table->dropForeign(['employee_id']);

            // Make employee_id nullable and re-add FK with nullOnDelete
            $table->foreignId('employee_id')->nullable()->change();
            $table->foreign('employee_id')->references('id')->on('employees')->nullOnDelete();
            $table->unique(['employee_id']); // still unique when set

            // Add person_id as alternative link for freelancers
            $table->foreignId('person_id')->nullable()->after('employee_id')->constrained('people');
        });

        // Must have at least one of employee_id or person_id
        DB::statement('ALTER TABLE trainers ADD CONSTRAINT trainers_person_or_employee_check CHECK (employee_id IS NOT NULL OR person_id IS NOT NULL)');
    }

    public function down(): void
    {
        DB::statement('ALTER TABLE trainers DROP CONSTRAINT IF EXISTS trainers_person_or_employee_check');

        Schema::table('trainers', function (Blueprint $table) {
            $table->dropForeign(['person_id']);
            $table->dropColumn('person_id');

            $table->dropUnique(['employee_id']);
            $table->dropForeign(['employee_id']);

            $table->foreignId('employee_id')->nullable(false)->change();
            $table->foreign('employee_id')->references('id')->on('employees');
            $table->unique(['employee_id']);
        });
    }
};
