<?php

namespace Tests\Unit\Services\Parsers;

use App\Services\Parsers\VrtArticlePageParser;
use Tests\TestCase;

class VrtArticlePageParserTest extends TestCase
{
    public function test_extract_thumbnail_from_og_image(): void
    {
        $html = '<html><head><meta property="og:image" content="https://images.vrt.be/image.jpg"/></head></html>';

        $this->assertEquals(
            'https://images.vrt.be/image.jpg',
            VrtArticlePageParser::extractThumbnail($html)
        );
    }

    public function test_extract_thumbnail_falls_back_to_img_tag(): void
    {
        $html = '<html><body><img src="https://images.vrt.be/body.png" alt="test"/></body></html>';

        $this->assertEquals(
            'https://images.vrt.be/body.png',
            VrtArticlePageParser::extractThumbnail($html)
        );
    }

    public function test_extract_thumbnail_prefers_og_image(): void
    {
        $html = '<html><head><meta property="og:image" content="https://images.vrt.be/og.jpg"/></head>'
            .'<body><img src="https://images.vrt.be/body.png" alt="test"/></body></html>';

        $this->assertEquals(
            'https://images.vrt.be/og.jpg',
            VrtArticlePageParser::extractThumbnail($html)
        );
    }

    public function test_extract_thumbnail_returns_null_when_not_found(): void
    {
        $this->assertNull(VrtArticlePageParser::extractThumbnail('<html><body>No images</body></html>'));
    }

    public function test_extract_thumbnail_decodes_html_entities(): void
    {
        // Entity-encoded ampersands make the URL unusable downstream. See #117.
        $html = '<html><head><meta property="og:image" content="https://images.vrt.be/orig.jpg?crop=1&amp;w=1200"/></head></html>';

        $thumbnail = VrtArticlePageParser::extractThumbnail($html);

        $this->assertEquals('https://images.vrt.be/orig.jpg?crop=1&w=1200', $thumbnail);
        $this->assertStringNotContainsString('&amp;', (string) $thumbnail);
    }

    public function test_extract_thumbnail_decodes_html_entities_in_img_tag(): void
    {
        $html = '<html><body><img src="https://images.vrt.be/pic.png?a=1&amp;b=2" alt="test"/></body></html>';

        $this->assertEquals(
            'https://images.vrt.be/pic.png?a=1&b=2',
            VrtArticlePageParser::extractThumbnail($html)
        );
    }

    public function test_extract_data_returns_decoded_thumbnail(): void
    {
        $html = '<html><head><meta property="og:image" content="https://images.vrt.be/x.jpg?v=1&amp;m=2"/></head></html>';

        $data = VrtArticlePageParser::extractData($html);

        $this->assertEquals('https://images.vrt.be/x.jpg?v=1&m=2', $data['thumbnail']);
    }
}
