<?php

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

return new class extends Migration
{
    public function up(): void
    {
        // FK ke gurus yang masih ada: mengajars_nip_foreign
        Schema::table('mengajars', function (Blueprint $table) {
            $table->dropForeign('mengajars_nip_foreign');
        });

        // Tambah kolom id_guru
        Schema::table('gurus', function (Blueprint $table) {
            $table->unsignedBigInteger('id_guru')->nullable()->first();
        });

        // Isi nomor urut
        DB::statement('SET @n = 0');
        DB::statement('UPDATE gurus SET id_guru = (@n := @n + 1) ORDER BY nip');

        // Hapus PK nip
        DB::statement('ALTER TABLE gurus DROP PRIMARY KEY');

        // Jadikan id_guru sebagai PK AUTO_INCREMENT
        DB::statement('ALTER TABLE gurus MODIFY id_guru BIGINT UNSIGNED NOT NULL AUTO_INCREMENT, ADD PRIMARY KEY (id_guru)');

        // Jadikan nip UNIQUE
        Schema::table('gurus', function (Blueprint $table) {
            $table->unique('nip', 'gurus_nip_unique');
        });
    }

    public function down(): void
    {
        throw new \Exception('Rollback tidak didukung. Restore dari backup.');
    }
};