<?php

namespace Mtc\Plugins\BlockManager\Tests\Feature;

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

class PreviewApiTest extends TestCase
{
    /** @var string[] */
    private array $createdUuids = [];

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

    public function test_preview_returns_404_for_unknown_id(): void
    {
        $this->postJson('/api/block-manager/variants/99999999/preview')->assertStatus(404);
    }

    public function test_preview_returns_200_with_html_css_warnings(): void
    {
        $draft = $this->seedDraft('button');

        $response = $this->postJson("/api/block-manager/variants/{$draft->id}/preview");
        $response->assertStatus(200);

        $data = $response->json('data');
        $this->assertIsArray($data);
        foreach (['html', 'css', 'warnings'] as $key) {
            $this->assertArrayHasKey($key, $data, "Preview response missing '{$key}'.");
        }
        $this->assertIsArray($data['warnings']);
    }

    public function test_preview_accepts_inline_properties_json_override(): void
    {
        $draft = $this->seedDraft('button');

        $response = $this->postJson("/api/block-manager/variants/{$draft->id}/preview", [
            'properties_json' => [
                'base' => ['default' => ['desktop' => [
                    'background' => ['color' => ['raw' => '#abcdef']],
                ]]],
            ],
        ]);
        $response->assertStatus(200);

        $css = $response->json('data.css');
        $this->assertStringContainsString(
            'background-color: #abcdef',
            $css,
            "Inline properties_json override should produce matching CSS without persisting the draft."
        );

        // Persisted state must NOT have been touched
        $fresh = BlockManagerVariantDraft::find($draft->id);
        $this->assertNull($fresh->properties_json, "Preview must NOT persist the inline override.");
    }

    public function test_preview_resolves_color_token_in_response_css(): void
    {
        $draft = $this->seedDraft('button');

        $response = $this->postJson("/api/block-manager/variants/{$draft->id}/preview", [
            'properties_json' => [
                'base' => ['default' => ['desktop' => [
                    'typography' => ['color' => ['token' => '@primary_color']],
                ]]],
            ],
        ]);
        $response->assertStatus(200);

        $css = $response->json('data.css');
        $this->assertMatchesRegularExpression(
            '/color:\s*#[0-9a-fA-F]+/',
            $css,
            "Preview CSS must resolve the color token to its hex value."
        );
        $this->assertStringNotContainsString(
            '@primary_color',
            $css,
            "Preview CSS must NOT contain the literal '@primary_color' token name."
        );
    }

    public function test_preview_html_matches_element_type(): void
    {
        $heading = $this->seedDraft('heading');
        $button  = $this->seedDraft('button');

        $headingHtml = $this->postJson("/api/block-manager/variants/{$heading->id}/preview")
            ->json('data.html');
        $buttonHtml = $this->postJson("/api/block-manager/variants/{$button->id}/preview")
            ->json('data.html');

        $this->assertMatchesRegularExpression(
            '/<h[1-6]/',
            $headingHtml,
            "Heading preview must contain a heading tag."
        );
        $this->assertStringContainsString(
            '<button',
            $buttonHtml,
            "Button preview must contain a <button> tag."
        );
    }

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

        return BlockManagerVariantDraft::create([
            'uuid'            => $uuid,
            'element_type'    => $elementType,
            'variant_slug'    => 'phase10-api-' . Str::random(8),
            'label'           => 'Phase 10 API Probe',
            'properties_json' => null,
        ]);
    }
}
