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

        Schema::table('company_user', function (Blueprint $table) {
            if (Schema::hasTable('companies')) {
                $table->foreign('company_id', 'cu_company_fk')
                      ->references('id')->on('companies')
                      ->onUpdate('cascade')
                      ->onDelete('cascade');
            }

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

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

        Schema::table('company_user', function (Blueprint $table) {
            try { $table->dropForeign('cu_company_fk'); } catch (\Throwable $e) {}
            try { $table->dropForeign('cu_user_fk'); } catch (\Throwable $e) {}
        });
    }
};

