<?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
{
    public function up(): void
    {
        Schema::table('managed_environments', function (Blueprint $table): void {
            $table->timestamp('removed_from_workspace_at')->nullable()->after('deleted_at');
            $table->foreignId('removed_from_workspace_by_user_id')->nullable()->after('removed_from_workspace_at')->constrained('users')->nullOnDelete();
            $table->text('removed_from_workspace_reason')->nullable()->after('removed_from_workspace_by_user_id');

            $table->index('removed_from_workspace_at');
        });

        if (DB::getDriverName() === 'sqlite') {
            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');
        }
    }

    public function down(): void
    {
        Schema::table('managed_environments', function (Blueprint $table): void {
            $table->dropIndex(['removed_from_workspace_at']);
            $table->dropConstrainedForeignId('removed_from_workspace_by_user_id');
            $table->dropColumn([
                'removed_from_workspace_at',
                'removed_from_workspace_reason',
            ]);
        });
    }
};
