<?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
{
    /**
     * Run the migrations.
     */
    public function up(): void
    {
        Schema::table('users', function (Blueprint $table) {
            $table->foreignId('unit_kerja_id')
                ->nullable()
                ->after('role')
                ->constrained('unit_kerja')
                ->nullOnDelete();
        });

        $defaultUnitKerjaId = DB::table('unit_kerja')->orderBy('id')->value('id');

        if ($defaultUnitKerjaId) {
            DB::table('users')
                ->where('role', 'admin')
                ->whereNull('unit_kerja_id')
                ->update(['unit_kerja_id' => $defaultUnitKerjaId]);
        }
    }

    /**
     * Reverse the migrations.
     */
    public function down(): void
    {
        Schema::table('users', function (Blueprint $table) {
            $table->dropConstrainedForeignId('unit_kerja_id');
        });
    }
};
