<?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
    {
        // Create only if it doesn't exist (safe on hosts where you already created it manually)
        if (! Schema::hasTable('company_user')) {
            Schema::create('company_user', function (Blueprint $table) {
                $table->unsignedBigInteger('company_id');
                $table->unsignedBigInteger('user_id');

                // prevent duplicates
                $table->unique(['company_id', 'user_id'], 'company_user_unique');

                // Optional: add FKs if you want automatic cascade cleanup.
                // If you previously had FK issues, leave these commented.
                $table->foreign('company_id')->references('id')->on('companies')->onDelete('cascade');
                $table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
            });
        } else {
            Schema::table('company_user', function (Blueprint $table) {
                $sm = Schema::getConnection()->getDoctrineSchemaManager();
                $indexes = array_map('strtolower', array_keys($sm->listTableIndexes('company_user')));
                if (! in_array('company_user_unique', $indexes)) {
                    $table->unique(['company_id', 'user_id'], 'company_user_unique');
                }
            });
        }
    }

    public function down(): void
    {
        Schema::dropIfExists('company_user');
    }
};