<?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('designation_user')) return;

        Schema::table('designation_user', function (Blueprint $table) {
            if (Schema::hasTable('designations')) {
                $table->foreign('designation_id', 'dgu_designation_fk')
                      ->references('id')->on('designations')
                      ->onUpdate('cascade')
                      ->onDelete('cascade'); // typical for pivot
            }

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

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

        Schema::table('designation_user', function (Blueprint $table) {
            try { $table->dropForeign('dgu_designation_fk'); } catch (\Throwable $e) {}
            try { $table->dropForeign('dgu_user_fk'); } catch (\Throwable $e) {}
        });
    }
};

