<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

return new class extends Migration
{
    /**
     * Block Templates — reusable collections of block definitions
     * that can be applied to entities in one click.
     */
    public function up(): void
    {
        // Block template definitions
        Schema::create('block_templates', function (Blueprint $table) {
            $table->increments('id');
            $table->string('name', 255);
            $table->string('slug', 255)->unique();
            $table->text('description')->nullable();
            $table->timestamps();
        });

        // Blocks belonging to a template (references, not content)
        Schema::create('block_template_items', function (Blueprint $table) {
            $table->increments('id');
            $table->unsignedInteger('block_template_id');
            $table->unsignedInteger('block_id');
            $table->integer('order_index')->default(0);
            $table->timestamps();

            $table->foreign('block_template_id', 'bt_items_template_fk')
                ->references('id')->on('block_templates')
                ->onDelete('cascade');

            $table->foreign('block_id', 'bt_items_block_fk')
                ->references('id')->on('block_registry')
                ->onDelete('cascade');

            $table->unique(['block_template_id', 'block_id'], 'bt_items_template_block_unique');
            $table->index(['block_template_id', 'order_index'], 'bt_items_template_order_idx');
        });

        // Which page templates a block template is available on
        Schema::create('block_template_assignments', function (Blueprint $table) {
            $table->increments('id');
            $table->unsignedInteger('block_template_id');
            $table->string('template_name', 64);
            $table->timestamps();

            $table->foreign('block_template_id', 'bt_assign_template_fk')
                ->references('id')->on('block_templates')
                ->onDelete('cascade');

            $table->unique(['block_template_id', 'template_name'], 'bt_assign_template_unique');
            $table->index('template_name', 'bt_assign_template_name_idx');
        });
    }

    public function down(): void
    {
        Schema::dropIfExists('block_template_assignments');
        Schema::dropIfExists('block_template_items');
        Schema::dropIfExists('block_templates');
    }
};
