<?php

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

return new class extends Migration
{
    public function up(): void
    {
        if (! Schema::hasTable('managed_environment_permissions') || Schema::hasColumn('managed_environment_permissions', 'workspace_id')) {
            return;
        }

        Schema::table('managed_environment_permissions', function (Blueprint $table): void {
            $table->unsignedBigInteger('workspace_id')->nullable();
            $table->index('workspace_id');
            $table->index(['workspace_id', 'managed_environment_id']);
        });
    }

    public function down(): void
    {
        if (! Schema::hasTable('managed_environment_permissions') || ! Schema::hasColumn('managed_environment_permissions', 'workspace_id')) {
            return;
        }

        Schema::table('managed_environment_permissions', function (Blueprint $table): void {
            $table->dropIndex(['workspace_id', 'managed_environment_id']);
            $table->dropIndex(['workspace_id']);
            $table->dropColumn('workspace_id');
        });
    }
};
