<?php

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

/**
 * MIGRATION ORDER NOTES
 * ---------------------
 * departments (000001) — no FK to users. head_user_id is a plain nullable
 *   unsigned integer here; its FK to users is added in 000007 AFTER users exists.
 *
 * users (000002) — NO department_id column. A user's department is derived
 *   through the employees table (users → employees → departments). Storing
 *   department_id on users would create a circular FK dependency with this
 *   table and is therefore intentionally omitted.
 */
return new class extends Migration
{
    public function up(): void
    {
        Schema::create('departments', function (Blueprint $table) {
            $table->id();
            $table->string('name');
            $table->string('code')->unique()->nullable();
            $table->enum('type', ['college', 'division', 'department', 'unit'])
                  ->default('department');
            $table->foreignId('parent_id')
                  ->nullable()
                  ->constrained('departments')
                  ->nullOnDelete();

            // head_user_id FK is deferred to migration 000007.
            // At this point the users table does not yet exist, so we store
            // only the raw integer — the foreign key constraint is added later.
            $table->unsignedBigInteger('head_user_id')->nullable()->index();

            $table->string('location')->nullable();
            $table->text('description')->nullable();
            $table->boolean('is_active')->default(true);
            $table->timestamps();
        });
    }

    public function down(): void
    {
        Schema::dropIfExists('departments');
    }
};
