<?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
    {
        // 1. Hapus semua kemungkinan Foreign Key lama agar tidak bentrok
        try {
            DB::statement('ALTER TABLE peminjaman DROP FOREIGN KEY peminjaman_ibfk_1');
        } catch (\Exception $e) {
        }
        try {
            DB::statement('ALTER TABLE peminjaman DROP FOREIGN KEY peminjaman_ibfk_2');
        } catch (\Exception $e) {
        }
        try {
            DB::statement('ALTER TABLE peminjaman DROP FOREIGN KEY fk_peminjaman_user');
        } catch (\Exception $e) {
        }
        try {
            DB::statement('ALTER TABLE peminjaman DROP FOREIGN KEY fk_peminjaman_buku');
        } catch (\Exception $e) {
        }

        // Menghapus default foreign key dari Laravel
        try {
            Schema::table('peminjaman', function (Blueprint $table) {
                $table->dropForeign(['id_user']);
            });
        } catch (\Exception $e) {
        }
        try {
            Schema::table('peminjaman', function (Blueprint $table) {
                $table->dropForeign(['id_buku']);
            });
        } catch (\Exception $e) {
        }

        // 2. Samakan Tipe Data (Ditaruh di LUAR Schema::table agar pasti dieksekusi duluan)
        DB::statement('ALTER TABLE peminjaman MODIFY id_user BIGINT UNSIGNED NOT NULL');
        DB::statement('ALTER TABLE peminjaman MODIFY id_buku BIGINT UNSIGNED NOT NULL');

        // 3. Buat Relasi Baru yang Benar
        Schema::table('peminjaman', function (Blueprint $table) {
            $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) {
            // Hapus kedua relasi jika migration di-rollback
            $table->dropForeign(['id_user']);
            $table->dropForeign(['id_buku']);
        });
    }
};
