<?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
{
    /**
     * Allow block-template items to reference a global block instead of (or as
     * well as) a block definition. When source_block_id is set, the item is a
     * global-block reference; when null, the item is a fresh block-type slot
     * that will be materialised as a new EntityBlock on apply.
     *
     * Also drops the (block_template_id, block_id) unique constraint so a
     * template can include the same block_id more than once — e.g. two CTA
     * blocks, or a global-block reference alongside a fresh block of the same
     * type.
     */
    public function up(): void
    {
        Schema::table('block_template_items', function (Blueprint $table) {
            $table->dropUnique('bt_items_template_block_unique');
        });

        Schema::table('block_template_items', function (Blueprint $table) {
            $table->unsignedInteger('source_block_id')->nullable()->after('block_id');

            $table->foreign('source_block_id', 'bt_items_source_block_fk')
                ->references('id')->on('entity_blocks')
                ->onDelete('cascade');

            $table->index('source_block_id', 'bt_items_source_block_idx');
        });
    }

    public function down(): void
    {
        Schema::table('block_template_items', function (Blueprint $table) {
            $table->dropForeign('bt_items_source_block_fk');
            $table->dropIndex('bt_items_source_block_idx');
            $table->dropColumn('source_block_id');
        });

        // The up-migration deliberately allowed duplicate (block_template_id,
        // block_id) rows. Collapse any that exist to the lowest-id row per pair
        // so re-adding the unique constraint below can succeed.
        DB::statement('
            DELETE b FROM block_template_items b
            INNER JOIN block_template_items a
                ON a.block_template_id = b.block_template_id
                AND a.block_id = b.block_id
                AND a.id < b.id
        ');

        Schema::table('block_template_items', function (Blueprint $table) {
            $table->unique(['block_template_id', 'block_id'], 'bt_items_template_block_unique');
        });
    }
};
