<?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 kelas sudah tidak ada, langsung proses

        // 1. Tambah kolom integer sementara
        Schema::table('kelas', function (Blueprint $table) {
            $table->unsignedBigInteger('id_kelas_baru')->nullable()->after('id_kelas');
        });

        // 2. Isi dengan nomor urut
        DB::statement('SET @n = 0');
        DB::statement('UPDATE kelas SET id_kelas_baru = (@n := @n + 1) ORDER BY id_kelas');

        // 3. Hapus PK lama (aman karena FK sudah tidak ada)
        DB::statement('ALTER TABLE kelas DROP PRIMARY KEY');

        // 4. Jadikan AUTO_INCREMENT PK
        DB::statement('ALTER TABLE kelas MODIFY id_kelas_baru BIGINT UNSIGNED NOT NULL AUTO_INCREMENT, ADD PRIMARY KEY (id_kelas_baru)');

        // 5. Rename kolom
        DB::statement('ALTER TABLE kelas CHANGE id_kelas id_kelas_old VARCHAR(20)');
        DB::statement('ALTER TABLE kelas CHANGE id_kelas_baru id_kelas BIGINT UNSIGNED NOT NULL AUTO_INCREMENT');
    }

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