<?php

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

return new class extends Migration
{
    /**
     * Entity blocks — runtime block instances for pages, items, categories.
     */
    public function up(): void
    {
        if (Schema::hasTable('entity_blocks')) {
            return;
        }

        Schema::create('entity_blocks', function (Blueprint $table) {
            $table->increments('id');
            $table->string('entity_type', 50)->default('page');
            $table->unsignedInteger('entity_id');
            $table->unsignedInteger('block_id');
            $table->integer('order')->default(0);
            $table->json('data')->nullable();
            $table->string('structure_hash', 64)->nullable();
            $table->string('status', 20)->default('draft');
            $table->unsignedInteger('source_block_id')->nullable();
            $table->string('name', 255)->nullable();
            $table->string('preview_image', 255)->nullable();
            $table->timestamps();

            $table->index(['entity_type', 'entity_id'], 'entity_blocks_entity_index');
            $table->index('block_id');
            $table->index(['entity_type', 'entity_id', 'order'], 'entity_blocks_order_index');
            $table->index('status');
            $table->index('source_block_id');
            $table->index(['entity_type', 'entity_id', 'status'], 'entity_blocks_entity_status_index');

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

            $table->foreign('source_block_id')
                ->references('id')
                ->on('entity_blocks')
                ->onDelete('set null');
        });
    }

    /**
     * Reverse the migrations.
     */
    public function down(): void
    {
        Schema::dropIfExists('entity_blocks');
    }
};
