<?php

namespace Tests\Unit\Services;

use App\Enums\LandingPageVersion;
use App\Services\CatalogTemplateLocator;
use Tests\TestCase;

class CatalogTemplateLocatorTest extends TestCase
{
    public function test_it_lists_template_folders_that_contain_index_phtml(): void
    {
        config(['landing-page-templates.path' => base_path('tests/Fixtures/catalog-templates')]);

        $locator = new CatalogTemplateLocator;

        $this->assertSame(['template-1', 'template-2'], $locator->templatesFor(LandingPageVersion::Benefits));
        $this->assertSame([], $locator->templatesFor(LandingPageVersion::Offer));

        $slots = $locator->slots();

        $this->assertCount(1, $slots);
        $this->assertSame(LandingPageVersion::Benefits, $slots[0]['version']);
        $this->assertArrayNotHasKey('template', $slots[0]);
        $this->assertSame(['template-1', 'template-2'], $locator->sharedTemplates());
    }

    public function test_it_inlines_preview_css_for_a_template_html_file(): void
    {
        config(['landing-page-templates.path' => base_path('tests/Fixtures/catalog-templates')]);

        $html = (new CatalogTemplateLocator)->previewDocument('template-1');

        $this->assertIsString($html);
        $this->assertStringContainsString('Preview fixture one', $html);
        $this->assertStringContainsString('data:text/css;base64,', $html);
        $this->assertStringNotContainsString('href="style.css"', $html);
    }

    public function test_it_returns_null_for_an_unknown_preview_template(): void
    {
        config(['landing-page-templates.path' => base_path('tests/Fixtures/catalog-templates')]);

        $this->assertNull((new CatalogTemplateLocator)->previewDocument('../secrets'));
    }

    public function test_it_reuses_a_stored_template_name(): void
    {
        config(['landing-page-templates.path' => base_path('tests/Fixtures/catalog-templates')]);

        $this->assertSame(
            'template-2',
            (new CatalogTemplateLocator)->pickTemplate(LandingPageVersion::Benefits, 'template-2'),
        );
    }

    public function test_it_picks_from_available_templates_when_none_is_stored(): void
    {
        config(['landing-page-templates.path' => base_path('tests/Fixtures/catalog-templates')]);

        $this->assertContains(
            (new CatalogTemplateLocator)->pickTemplate(LandingPageVersion::Benefits),
            ['template-1', 'template-2'],
        );
    }
}
