<?php

declare(strict_types=1);

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

return new class extends Migration
{
    public function up(): void
    {
        Schema::create('operational_control_activations', function (Blueprint $table): void {
            $table->id();
            $table->string('control_key');
            $table->string('scope_type');
            $table->foreignId('workspace_id')->nullable()->constrained('workspaces')->cascadeOnDelete();
            $table->text('reason_text');
            $table->timestampTz('expires_at')->nullable();
            $table->foreignId('created_by_platform_user_id')->constrained('platform_users')->restrictOnDelete();
            $table->foreignId('updated_by_platform_user_id')->nullable()->constrained('platform_users')->nullOnDelete();
            $table->timestamps();

            $table->index(['control_key', 'scope_type']);
            $table->index(['workspace_id', 'control_key']);
            $table->index('expires_at');
        });

        DB::statement("CREATE UNIQUE INDEX operational_control_activations_global_unique ON operational_control_activations (control_key) WHERE scope_type = 'global'");
        DB::statement("CREATE UNIQUE INDEX operational_control_activations_workspace_unique ON operational_control_activations (control_key, workspace_id) WHERE scope_type = 'workspace' AND workspace_id IS NOT NULL");
    }

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