<?php

namespace Tests\Unit;

use App\Domain\Blog\AttachEmbed;
use App\Domain\Blog\ContentFormat;
use App\Domain\Blog\ContentRenderer;
use Tests\TestCase;

class AttachEmbedTest extends TestCase
{
    public function test_legacy_token_converts_to_markdown_safe_reference(): void
    {
        $md = app(AttachEmbed::class)->legacyToMarkdownReference('see [attach=12] please');

        $this->assertStringContainsString('(attach:12)', $md);
        $this->assertStringNotContainsString('[attach=12]', $md);
    }

    public function test_markdown_render_expands_attach_protocol_to_entry_url(): void
    {
        $html = app(ContentRenderer::class)->toHtml(
            "![x](attach:42)\n",
            ContentFormat::MARKDOWN,
        );

        $this->assertStringContainsString('/attachment.php?id=42', $html);
        $this->assertStringNotContainsString('attach:42', $html);
    }

    public function test_html_render_hydrates_legacy_attach_token(): void
    {
        $html = app(ContentRenderer::class)->toHtml(
            '<p>file [attach=7]</p>',
            ContentFormat::HTML,
        );

        $this->assertStringContainsString('/attachment.php?id=7', $html);
        $this->assertStringNotContainsString('[attach=7]', $html);
    }

    public function test_html_img_src_attach_attribute_is_not_nested(): void
    {
        $html = app(ContentRenderer::class)->toHtml(
            '<p><img src="[attach=1]" alt="pic"></p>',
            ContentFormat::HTML,
        );

        $this->assertStringContainsString('src="'.url('/attachment.php?id=1').'"', $html);
        $this->assertStringNotContainsString('src="<img', $html);
        $this->assertStringNotContainsString('[attach=1]', $html);
    }

    public function test_markdown_import_conversion_protects_attach_tokens(): void
    {
        $md = app(ContentRenderer::class)->convertImportedHtmlToMarkdown(
            '<p><img src="[attach=1]" alt="pic"> and [attach=2]</p>'
        );

        $this->assertStringContainsString('(attach:1)', $md);
        $this->assertStringContainsString('(attach:2)', $md);
        $this->assertStringNotContainsString('![](![', $md);
        $this->assertStringNotContainsString('\[attach=', $md);
    }
}

