<?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 siswas yang masih ada:
        // leaderboards_nisn_foreign, pengumpulan_tugas_nisn_foreign,
        // peserta_challenges_nisn_foreign, siswa_badges_nisn_foreign

        Schema::table('leaderboards', function (Blueprint $table) {
            $table->dropForeign('leaderboards_nisn_foreign');
        });
        Schema::table('pengumpulan_tugas', function (Blueprint $table) {
            $table->dropForeign('pengumpulan_tugas_nisn_foreign');
        });
        Schema::table('peserta_challenges', function (Blueprint $table) {
            $table->dropForeign('peserta_challenges_nisn_foreign');
        });
        Schema::table('siswa_badges', function (Blueprint $table) {
            $table->dropForeign('siswa_badges_nisn_foreign');
        });

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

        // Isi nomor urut
        DB::statement('SET @n = 0');
        DB::statement('UPDATE siswas SET id_siswa = (@n := @n + 1) ORDER BY nisn');

        // Hapus PK nisn
        DB::statement('ALTER TABLE siswas DROP PRIMARY KEY');

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

        // Jadikan nisn UNIQUE
        Schema::table('siswas', function (Blueprint $table) {
            $table->unique('nisn', 'siswas_nisn_unique');
        });
    }

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