<?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('environments', function (Blueprint $table) {
            $table->dropUnique('environments_domain_unique');
        });

        // Objetivo: el dominio sigue siendo único entre entornos NO locales, pero los
        // locales pueden repetirlo (ver fixes/PRODSECU-192).
        //
        // MySQL no admite índices parciales, así que se emula con una columna generada
        // que vale NULL cuando env='local' (los NULL no colisionan en un índice único).
        // El resto de motores sí admiten índice parcial, que expresa lo mismo de forma
        // directa — y así la suite de tests puede correr sobre sqlite (known-issues MGR-019).
        if (DB::getDriverName() === 'mysql') {
            DB::statement("
                ALTER TABLE environments
                ADD COLUMN domain_unique VARCHAR(255)
                GENERATED ALWAYS AS (CASE WHEN env = 'local' THEN NULL ELSE domain END) STORED
            ");

            Schema::table('environments', function (Blueprint $table) {
                $table->unique('domain_unique', 'environments_domain_unique');
            });

            return;
        }

        DB::statement("
            CREATE UNIQUE INDEX environments_domain_unique
            ON environments (domain)
            WHERE env <> 'local'
        ");
    }

    public function down(): void
    {
        if (DB::getDriverName() === 'mysql') {
            Schema::table('environments', function (Blueprint $table) {
                $table->dropUnique('environments_domain_unique');
            });

            DB::statement('ALTER TABLE environments DROP COLUMN domain_unique');
        } else {
            DB::statement('DROP INDEX IF EXISTS environments_domain_unique');
        }

        Schema::table('environments', function (Blueprint $table) {
            $table->unique('domain', 'environments_domain_unique');
        });
    }
};