<?php

namespace Mtc\Plugins\BlockManager\Tests\Unit;

use Illuminate\Support\Str;
use Mtc\Plugins\BlockManager\Models\BlockManagerBlock;
use Tests\TestCase;

class BlockManagerBlockModelTest extends TestCase
{
    private array $createdUuids = [];

    protected function tearDown(): void
    {
        if (!empty($this->createdUuids)) {
            BlockManagerBlock::whereIn('uuid', $this->createdUuids)->delete();
        }
        parent::tearDown();
    }

    public function test_model_table_name(): void
    {
        $this->assertSame('block_manager_blocks', (new BlockManagerBlock())->getTable());
    }

    public function test_model_fillable_columns(): void
    {
        $fillable = (new BlockManagerBlock())->getFillable();

        foreach (['uuid', 'slug', 'name', 'description', 'category_id', 'icon', 'structure_json', 'last_shipped_at', 'shipped_block_registry_id'] as $column) {
            $this->assertContains(
                $column,
                $fillable,
                "BlockManagerBlock::\$fillable is missing '{$column}'."
            );
        }
    }

    public function test_model_structure_json_is_cast_to_array(): void
    {
        $casts = (new BlockManagerBlock())->getCasts();

        $this->assertArrayHasKey('structure_json', $casts);
        $this->assertSame('array', $casts['structure_json']);
    }

    public function test_model_last_shipped_at_is_cast_to_datetime(): void
    {
        $casts = (new BlockManagerBlock())->getCasts();

        $this->assertArrayHasKey('last_shipped_at', $casts);
        $this->assertContains($casts['last_shipped_at'], ['datetime', 'immutable_datetime']);
    }

    public function test_model_can_persist_and_retrieve(): void
    {
        $uuid = (string) Str::uuid();
        $this->createdUuids[] = $uuid;

        $block = BlockManagerBlock::create([
            'uuid' => $uuid,
            'slug' => 'phase1-roundtrip-' . Str::random(8),
            'name' => 'Phase 1 Round-trip',
            'description' => 'Round-trip probe',
            'icon' => 'fa-cube',
            'structure_json' => [
                'elements' => [
                    ['instance_id' => 'el-001', 'element_type' => 'heading', 'variant' => 'default'],
                ],
            ],
        ]);

        $fresh = BlockManagerBlock::where('uuid', $uuid)->firstOrFail();

        $this->assertSame('Phase 1 Round-trip', $fresh->name);
        $this->assertIsArray($fresh->structure_json);
        $this->assertSame('heading', $fresh->structure_json['elements'][0]['element_type']);
    }
}
