<?php

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
{
    /**
     * Run the migrations.
     */
    public function up(): void
    {
        $driver = DB::getDriverName();

        if (! Schema::hasColumn('managed_environments', 'workspace_id')) {
            Schema::table('managed_environments', function (Blueprint $table): void {
                $table->foreignId('workspace_id')->nullable()->constrained()->cascadeOnDelete();
                $table->index(['workspace_id', 'lifecycle_status']);
                $table->index(['workspace_id', 'kind']);
            });
        }

        if ($driver === 'sqlite') {
            // SQLite table rebuilds can drop/flatten the partial index defined in
            // 2025_12_11_192942_add_is_current_to_tenants.php. Recreate it here.
            DB::statement('DROP INDEX IF EXISTS managed_environments_current_unique');
            DB::statement('CREATE UNIQUE INDEX managed_environments_current_unique ON managed_environments (is_current) WHERE is_current = 1 AND deleted_at IS NULL');
        }
    }

    /**
     * Reverse the migrations.
     */
    public function down(): void
    {
        Schema::hasTable('managed_environments');
    }
};
