<?php

namespace Mtc\Plugins\BlockManager\Tests\Unit;

use Mtc\Plugins\BlockManager\Services\DesignTokenService;
use Tests\TestCase;

class DesignTokenServiceTest extends TestCase
{
    private DesignTokenService $service;

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

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

    public function test_list_returns_array_of_tokens_with_expected_shape(): void
    {
        $tokens = $this->service->list();

        $this->assertIsArray($tokens);
        $this->assertNotEmpty($tokens, 'Token list must not be empty — variables.less should yield tokens.');

        foreach ($tokens as $token) {
            $this->assertIsArray($token);
            foreach (['name', 'type', 'value'] as $key) {
                $this->assertArrayHasKey($key, $token, "Token missing key '{$key}'.");
            }
            $this->assertStringStartsWith('@', (string) $token['name'], 'Token names must keep the @ prefix from variables.less.');
        }
    }

    public function test_list_classifies_primary_color_as_color(): void
    {
        $token = $this->findToken('@primary_color');

        $this->assertNotNull($token, '@primary_color must appear in the token list.');
        $this->assertSame('color', $token['type'], '@primary_color must be classified as a color.');
        $this->assertMatchesRegularExpression(
            '/^#[0-9a-fA-F]+$/',
            (string) $token['value'],
            '@primary_color value must be a hex color.'
        );
    }

    public function test_list_classifies_gutter_width_as_length(): void
    {
        $token = $this->findToken('@gutter_width');

        $this->assertNotNull($token, '@gutter_width must appear in the token list.');
        $this->assertSame('length', $token['type'], '@gutter_width must be classified as a length.');
        $this->assertMatchesRegularExpression(
            '/^\d+(\.\d+)?(px|em|rem|%|vh|vw)$/',
            (string) $token['value'],
            '@gutter_width value must be a CSS length.'
        );
    }

    public function test_get_returns_token_for_known_name(): void
    {
        $token = $this->service->get('@primary_color');

        $this->assertIsArray($token);
        $this->assertSame('@primary_color', $token['name']);
        $this->assertSame('color', $token['type']);
    }

    public function test_get_returns_null_for_unknown_token(): void
    {
        $this->assertNull($this->service->get('@does_not_exist_' . uniqid()));
    }

    private function findToken(string $name): ?array
    {
        foreach ($this->service->list() as $token) {
            if (($token['name'] ?? null) === $name) {
                return $token;
            }
        }
        return null;
    }
}
