<?php

namespace Mtc\Plugins\BlockManager\Tests\Unit;

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

class VariantLessParserTest extends TestCase
{
    private VariantLessParser $parser;

    /** @var string[] */
    private array $createdUuids = [];

    protected function setUp(): void
    {
        parent::setUp();
        $this->parser = app(VariantLessParser::class);
    }

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

    public function test_service_is_resolvable_from_container(): void
    {
        $this->assertInstanceOf(VariantLessParser::class, $this->parser);
    }

    public function test_parses_designer_meta_header_into_array(): void
    {
        $properties = ['base' => ['default' => ['desktop' => ['typography' => ['color' => ['raw' => '#123456']]]]]];
        $meta = [
            'version'      => 1,
            'element_type' => 'button',
            'variant_slug' => 'phase14-parser-' . Str::random(6),
            'properties'   => $properties,
        ];
        $less = '/* @designer-meta ' . json_encode($meta, JSON_UNESCAPED_SLASHES) . " */\n"
              . ".bm-button--{$meta['variant_slug']} {\n"
              . "  color: #123456;\n"
              . "}\n";

        $parsed = $this->parser->parse($less);

        $this->assertIsArray($parsed);
        foreach (['version', 'element_type', 'variant_slug', 'properties'] as $key) {
            $this->assertArrayHasKey($key, $parsed, "Parsed meta missing key '{$key}'.");
        }
        $this->assertSame('button', $parsed['element_type']);
        $this->assertSame($meta['variant_slug'], $parsed['variant_slug']);
        $this->assertSame($properties, $parsed['properties']);
    }

    public function test_returns_null_for_less_without_designer_meta_header(): void
    {
        $less = ".bm-button--primary {\n  background-color: #0f55c4;\n  padding: 12px 24px;\n}\n";

        $this->assertNull(
            $this->parser->parse($less),
            "Hand-authored LESS (no @designer-meta header) must parse to null."
        );
    }

    public function test_round_trips_via_less_generator(): void
    {
        $properties = [
            'base' => [
                'default' => [
                    'desktop' => [
                        'background' => ['color' => ['raw' => '#ffffff']],
                        'typography' => ['font_size' => ['raw' => '16px']],
                    ],
                    'mobile' => [
                        'typography' => ['font_size' => ['raw' => '14px']],
                    ],
                ],
                'hover' => [
                    'desktop' => [
                        'background' => ['color' => ['token' => '@primary_color']],
                    ],
                ],
            ],
        ];

        $draft = $this->seedDraft('button', 'phase14-rt-' . Str::random(6), $properties);

        $less = app(VariantLessGenerator::class)->generate($draft);
        $parsed = $this->parser->parse($less);

        $this->assertIsArray($parsed);
        $this->assertSame(
            $properties,
            $parsed['properties'],
            "Round-trip via generator → parser must reproduce the original properties_json verbatim."
        );
    }

    private function seedDraft(string $elementType, string $variantSlug, array $properties): BlockManagerVariantDraft
    {
        $uuid = (string) Str::uuid();
        $this->createdUuids[] = $uuid;

        return BlockManagerVariantDraft::create([
            'uuid'            => $uuid,
            'element_type'    => $elementType,
            'variant_slug'    => $variantSlug,
            'label'           => 'Phase 14 Parser Probe',
            'properties_json' => $properties,
        ]);
    }
}
