<?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
    {
        if (! Schema::hasTable('managed_environment_onboarding_sessions')) {
            return;
        }

        if (! Schema::hasColumn('managed_environment_onboarding_sessions', 'cancelled_at')) {
            Schema::table('managed_environment_onboarding_sessions', function (Blueprint $table): void {
                $table->timestamp('cancelled_at')->nullable()->after('completed_at');
            });
        }

        DB::statement('DROP INDEX IF EXISTS managed_environment_onboarding_sessions_active_workspace_entra_unique');
        DB::statement('DROP INDEX IF EXISTS managed_environment_onboarding_sessions_active_environment_unique');

        DB::statement('CREATE UNIQUE INDEX managed_environment_onboarding_sessions_active_workspace_entra_unique ON managed_environment_onboarding_sessions (workspace_id, entra_tenant_id) WHERE completed_at IS NULL AND cancelled_at IS NULL');
        DB::statement('CREATE UNIQUE INDEX managed_environment_onboarding_sessions_active_environment_unique ON managed_environment_onboarding_sessions (managed_environment_id) WHERE completed_at IS NULL AND cancelled_at IS NULL AND managed_environment_id IS NOT NULL');
    }

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

        DB::statement('DROP INDEX IF EXISTS managed_environment_onboarding_sessions_active_workspace_entra_unique');
        DB::statement('DROP INDEX IF EXISTS managed_environment_onboarding_sessions_active_environment_unique');

        DB::statement('CREATE UNIQUE INDEX managed_environment_onboarding_sessions_active_workspace_entra_unique ON managed_environment_onboarding_sessions (workspace_id, entra_tenant_id) WHERE completed_at IS NULL');
        DB::statement('CREATE UNIQUE INDEX managed_environment_onboarding_sessions_active_environment_unique ON managed_environment_onboarding_sessions (managed_environment_id) WHERE completed_at IS NULL AND managed_environment_id IS NOT NULL');

        if (Schema::hasColumn('managed_environment_onboarding_sessions', 'cancelled_at')) {
            Schema::table('managed_environment_onboarding_sessions', function (Blueprint $table): void {
                $table->dropColumn('cancelled_at');
            });
        }
    }
};
