<?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
    {
        Schema::table('landing_pages', function (Blueprint $table) {
            $table->string('template')->default('');
        });

        // The replacement index goes on before the old one comes off. The foreign
        // key on landing_page_generation_id is served by the old unique index, and
        // MySQL refuses to drop the only index covering a constrained column:
        // "Cannot drop index ...: needed in a foreign key constraint", errno 1553.
        // The new index also leads with that column, so once it exists the old one
        // is free to go.
        Schema::table('landing_pages', function (Blueprint $table) {
            $table->unique(['landing_page_generation_id', 'version', 'template']);
        });

        Schema::table('landing_pages', function (Blueprint $table) {
            $table->dropUnique(['landing_page_generation_id', 'version']);
        });
    }

    public function down(): void
    {
        // Same ordering constraint as up(), in reverse.
        Schema::table('landing_pages', function (Blueprint $table) {
            $table->unique(['landing_page_generation_id', 'version']);
        });

        Schema::table('landing_pages', function (Blueprint $table) {
            $table->dropUnique(['landing_page_generation_id', 'version', 'template']);
        });

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