<?php

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

return new class extends Migration {
    public function up(): void
    {
        if (!Schema::hasTable('department_user')) return;

        Schema::table('department_user', function (Blueprint $table) {
            if (Schema::hasTable('departments')) {
                $table->foreign('department_id', 'du_department_fk')
                      ->references('id')->on('departments')
                      ->onUpdate('cascade')
                      ->onDelete('cascade'); // typical for pivot
            }

            if (Schema::hasTable('users')) {
                $table->foreign('user_id', 'du_user_fk')
                      ->references('id')->on('users')
                      ->onUpdate('cascade')
                      ->onDelete('cascade'); // typical for pivot
            }
        });
    }

    public function down(): void
    {
        if (!Schema::hasTable('department_user')) return;

        Schema::table('department_user', function (Blueprint $table) {
            try { $table->dropForeign('du_department_fk'); } catch (\Throwable $e) {}
            try { $table->dropForeign('du_user_fk'); } catch (\Throwable $e) {}
        });
    }
};
