<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Schema;

return new class extends Migration
{
    public function up(): void
    {
        try {
            DB::statement('ALTER TABLE peminjaman DROP FOREIGN KEY peminjaman_ibfk_2');
        } catch (\Throwable $e) {
        }

        try {
            DB::statement('ALTER TABLE peminjaman DROP FOREIGN KEY fk_peminjaman_buku');
        } catch (\Throwable $e) {
        }

        try {
            Schema::table('peminjaman', function (Blueprint $table) {
                $table->dropForeign(['id_buku']);
            });
        } catch (\Throwable $e) {
        }

        DB::statement('ALTER TABLE peminjaman MODIFY id_buku INT UNSIGNED NOT NULL');

        Schema::table('peminjaman', function (Blueprint $table) {
            $table->foreign('id_buku')
                ->references('id_buku')
                ->on('buku')
                ->cascadeOnDelete();
        });
    }

    public function down(): void
    {
        try {
            Schema::table('peminjaman', function (Blueprint $table) {
                $table->dropForeign(['id_buku']);
            });
        } catch (\Throwable $e) {
        }

        DB::statement('ALTER TABLE peminjaman MODIFY id_buku BIGINT UNSIGNED NOT NULL');

        Schema::table('peminjaman', function (Blueprint $table) {
            $table->foreign('id_buku')
                ->references('id')
                ->on('bukus')
                ->cascadeOnDelete();
        });
    }
};
