<?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
{
    /**
     * Run the migrations.
     */
    public function up(): void
    {
        Schema::table('peminjaman', function (Blueprint $table) {
            // Drop old FKs carefully
            try {
                DB::statement('ALTER TABLE peminjaman DROP FOREIGN KEY peminjaman_ibfk_1');
            } catch (\Exception $e) {
                // Ignore if not exists
            }

            try {
                DB::statement('ALTER TABLE peminjaman DROP FOREIGN KEY peminjaman_ibfk_2');
            } catch (\Exception $e) {
                // Ignore if not exists
            }

            // Change column types
            DB::statement('ALTER TABLE peminjaman MODIFY id_user BIGINT UNSIGNED NOT NULL');
            DB::statement('ALTER TABLE peminjaman MODIFY id_buku BIGINT UNSIGNED NOT NULL');

            // Add correct foreign keys
            $table->foreign('id_user')
                  ->references('id')
                  ->on('users')
                  ->onDelete('cascade');
            
            $table->foreign('id_buku')
                  ->references('id')
                  ->on('bukus')
                  ->onDelete('cascade');
        });
    }

    /**
     * Reverse the migrations.
     */
    public function down(): void
    {
        Schema::table('peminjaman', function (Blueprint $table) {
            $table->dropForeign(['id_user']);
            // We cannot easily recreate the "wrong" FK without knowing exact wrong definition, 
            // but usually we don't need to revert a fix to a broken state.
        });
    }
};
