<?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
    {
        Schema::table('mengajars', function (Blueprint $table) {
            $table->unsignedBigInteger('id_mapel_baru')->nullable()->after('id_mapel');
        });
        DB::statement("UPDATE mengajars m JOIN mapels mp ON m.id_mapel = mp.id_mapel_old SET m.id_mapel_baru = mp.id_mapel");
        Schema::table('mengajars', function (Blueprint $table) {
            $table->unsignedBigInteger('id_mapel_baru')->nullable(false)->change();
            $table->foreign('id_mapel_baru', 'mengajars_id_mapel_new_foreign')
                  ->references('id_mapel')->on('mapels')->onDelete('cascade');
        });
        Schema::table('mengajars', function (Blueprint $table) {
            $table->dropColumn('id_mapel');
        });
        DB::statement('ALTER TABLE mengajars CHANGE id_mapel_baru id_mapel BIGINT UNSIGNED NOT NULL');

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

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