<?php

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

return new class extends Migration
{
    /**
     * Run the migrations.
     */
    public function up(): void
    {
        Schema::table('users', function (Blueprint $table) {
            // Drop naming specific foreign keys and unique index
            $table->dropForeign(['company_id']);
            $table->dropForeign(['role_id']);
            $table->dropUnique('uq_users_company_email');
        });

        Schema::table('users', function (Blueprint $table) {
            // Make company_id and role_id nullable
            $table->unsignedBigInteger('company_id')->nullable()->change();
            $table->unsignedBigInteger('role_id')->nullable()->change();
            
            // Add is_super_admin flag
            $table->boolean('is_super_admin')->default(false)->after('role_id');
            
            // Re-add foreign keys as nullable
            $table->foreign('company_id')->references('id')->on('companies')->onDelete('cascade');
            $table->foreign('role_id')->references('id')->on('roles')->onDelete('cascade');
            
            // Global unique index on email
            $table->unique('email', 'uq_users_email');
        });
    }

    /**
     * Reverse the migrations.
     */
    public function down(): void
    {
        Schema::table('users', function (Blueprint $table) {
            $table->dropUnique('uq_users_email');
            $table->dropColumn('is_super_admin');
            
            $table->dropForeign(['company_id']);
            $table->dropForeign(['role_id']);
        });

        Schema::table('users', function (Blueprint $table) {
            $table->unsignedBigInteger('company_id')->nullable(false)->change();
            $table->unsignedBigInteger('role_id')->nullable(false)->change();
            
            $table->foreign('company_id')->references('id')->on('companies');
            $table->foreign('role_id')->references('id')->on('roles');
            
            $table->unique(['company_id', 'email'], 'uq_users_company_email');
        });
    }
};
