<?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
    {
        $tables = [
            'leaderboards',
            'pengumpulan_tugas',
            'peserta_challenges',
            'siswa_badges',
        ];

        foreach ($tables as $tabel) {
            Schema::table($tabel, function (Blueprint $table) {
                $table->unsignedBigInteger('id_siswa')->nullable()->after('nisn');
            });

            DB::statement("UPDATE {$tabel} t JOIN siswas s ON t.nisn = s.nisn SET t.id_siswa = s.id_siswa");

            Schema::table($tabel, function (Blueprint $table) use ($tabel) {
                $table->unsignedBigInteger('id_siswa')->nullable(false)->change();
                $table->foreign('id_siswa', "{$tabel}_id_siswa_new_foreign")
                      ->references('id_siswa')->on('siswas')->onDelete('cascade');
            });

            Schema::table($tabel, function (Blueprint $table) {
                $table->dropColumn('nisn');
            });
        }
    }

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