<?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
    {
        if (!Schema::hasTable('departments')) {
            return;
        }

        Schema::table('departments', function (Blueprint $table) {
            if (!Schema::hasColumn('departments', 'is_builtin')) {
                $table->boolean('is_builtin')->default(false)->after('is_system');
                $table->index('is_builtin');
            }
        });

        // Backfill: treat existing system departments as built-in.
        if (Schema::hasColumn('departments', 'is_builtin') && Schema::hasColumn('departments', 'is_system')) {
            DB::table('departments')
                ->where('is_system', true)
                ->update(['is_builtin' => true]);
        }
    }

    public function down(): void
    {
        if (!Schema::hasTable('departments')) {
            return;
        }

        Schema::table('departments', function (Blueprint $table) {
            if (Schema::hasColumn('departments', 'is_builtin')) {
                $table->dropIndex(['is_builtin']);
                $table->dropColumn('is_builtin');
            }
        });
    }
};

