<?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
    {
        Schema::table('managed_environments', function (Blueprint $table) {
            $table->boolean('is_current')->default(false)->after('lifecycle_status');
        });

        DB::table('managed_environments')->update(['is_current' => false]);

        $preferredCurrentId = DB::table('managed_environments')
            ->whereNull('deleted_at')
            ->where('lifecycle_status', 'active')
            ->orderBy('created_at')
            ->value('id');

        if ($preferredCurrentId === null) {
            $preferredCurrentId = DB::table('managed_environments')
                ->whereNull('deleted_at')
                ->where('lifecycle_status', 'active')
                ->orderBy('created_at')
                ->value('id');
        }

        if ($preferredCurrentId !== null) {
            DB::table('managed_environments')
                ->where('id', $preferredCurrentId)
                ->update(['is_current' => true]);
        }

        DB::statement('CREATE UNIQUE INDEX managed_environments_current_unique ON managed_environments (is_current) WHERE is_current = true AND deleted_at IS NULL');
    }

    /**
     * Reverse the migrations.
     */
    public function down(): void
    {
        DB::statement('DROP INDEX IF EXISTS managed_environments_current_unique');

        Schema::table('managed_environments', function (Blueprint $table) {
            $table->dropColumn('is_current');
        });
    }
};
