<?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('support_access_grants', function (Blueprint $table): void {
            $table->id();
            $table->foreignId('workspace_id')->constrained('workspaces')->cascadeOnDelete();
            $table->foreignId('requested_by_platform_user_id')->constrained('platform_users')->restrictOnDelete();
            $table->foreignId('approved_by_user_id')->nullable()->constrained('users')->nullOnDelete();
            $table->string('scope');
            $table->string('status');
            $table->string('approval_mode');
            $table->text('reason');
            $table->text('waiver_reason')->nullable();
            $table->unsignedInteger('ttl_minutes');
            $table->timestamp('requested_at');
            $table->timestamp('approved_at')->nullable();
            $table->timestamp('starts_at')->nullable();
            $table->timestamp('expires_at')->nullable();
            $table->timestamp('ended_at')->nullable();
            $table->timestamp('denied_at')->nullable();
            $table->timestamps();

            $table->index(['workspace_id', 'scope', 'status']);
            $table->index(['requested_by_platform_user_id', 'scope']);
            $table->index(['expires_at', 'status']);
        });

        if (DB::connection()->getDriverName() === 'pgsql') {
            DB::statement("ALTER TABLE support_access_grants ADD CONSTRAINT support_access_grants_scope_check CHECK (scope IN ('audit_view', 'workspace_recovery'))");
            DB::statement("ALTER TABLE support_access_grants ADD CONSTRAINT support_access_grants_status_check CHECK (status IN ('requested', 'active', 'denied', 'expired', 'ended'))");
            DB::statement("ALTER TABLE support_access_grants ADD CONSTRAINT support_access_grants_approval_mode_check CHECK (approval_mode IN ('auto', 'owner_required', 'ownerless_waiver'))");
        }

        DB::statement("CREATE UNIQUE INDEX support_access_grants_open_unique ON support_access_grants (workspace_id, requested_by_platform_user_id, scope) WHERE status IN ('requested', 'active')");
    }

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