<?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
    {
        if (Schema::hasColumn('users', 'role')) {
            DB::statement("ALTER TABLE users MODIFY role ENUM('admin', 'super_admin', 'pegawai') NOT NULL DEFAULT 'admin'");
        }

        Schema::table('users', function (Blueprint $table) {
            $table->foreignId('pegawai_id')
                ->nullable()
                ->after('unit_kerja_id')
                ->constrained('pegawai')
                ->nullOnDelete();

            $table->unique('pegawai_id');
        });
    }

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

        DB::table('users')
            ->where('role', 'pegawai')
            ->delete();

        if (Schema::hasColumn('users', 'role')) {
            DB::statement("ALTER TABLE users MODIFY role ENUM('admin', 'super_admin') NOT NULL DEFAULT 'admin'");
        }
    }
};
