<?php

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

/**
 * DEFERRED FOREIGN KEY
 * --------------------
 * Adds departments.head_user_id → users.id constraint.
 *
 * This runs AFTER both departments (000001) and users (000002) exist,
 * so the FK is safe to declare here.
 *
 * Note: theme columns are now created directly in the users migration (000002),
 * so this migration only handles the deferred FK.
 */
return new class extends Migration
{
    public function up(): void
    {
        Schema::table('departments', function (Blueprint $table) {
            // Guard: only add FK if the column exists and the constraint
            // doesn't already exist (safe for re-runs / existing installs).
            if (Schema::hasColumn('departments', 'head_user_id')) {
                $table->foreign('head_user_id')
                      ->references('id')->on('users')
                      ->nullOnDelete();
            }
        });
    }

    public function down(): void
    {
        Schema::table('departments', function (Blueprint $table) {
            $table->dropForeign(['head_user_id']);
        });
    }
};
