<?php

namespace Mtc\Plugins\BlockManager\Tests\Unit;

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

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

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

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

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

        foreach (['uuid', 'element_type', 'variant_slug', 'label', 'properties_json', 'last_published_at', 'published_twig_path', 'published_less_path'] as $column) {
            $this->assertContains(
                $column,
                $fillable,
                "BlockManagerVariantDraft::\$fillable is missing '{$column}'."
            );
        }
    }

    public function test_model_properties_json_is_cast_to_array(): void
    {
        $casts = (new BlockManagerVariantDraft())->getCasts();

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

    public function test_model_last_published_at_is_cast_to_datetime(): void
    {
        $casts = (new BlockManagerVariantDraft())->getCasts();

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

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

        $draft = BlockManagerVariantDraft::create([
            'uuid' => $uuid,
            'element_type' => 'button',
            'variant_slug' => 'phase1-roundtrip-' . Str::random(8),
            'label' => 'Phase 1 Round-trip',
            'properties_json' => [
                'element_type' => 'button',
                'base' => [
                    'default' => [
                        'desktop' => [
                            'background' => ['color' => ['token' => '@primary_color']],
                        ],
                    ],
                ],
            ],
        ]);

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

        $this->assertSame('button', $fresh->element_type);
        $this->assertIsArray($fresh->properties_json);
        $this->assertSame(
            '@primary_color',
            $fresh->properties_json['base']['default']['desktop']['background']['color']['token']
        );
    }
}
