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

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

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

        // 3. Hapus PK lama
        DB::statement('ALTER TABLE mapels DROP PRIMARY KEY');

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

        // 5. Rename kolom
        DB::statement('ALTER TABLE mapels CHANGE id_mapel id_mapel_old VARCHAR(20)');
        DB::statement('ALTER TABLE mapels CHANGE id_mapel_baru id_mapel BIGINT UNSIGNED NOT NULL AUTO_INCREMENT');
    }

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