<?php

namespace Tests\Unit\Services;

use App\Services\LandingPagePixelInjector;
use App\Services\PublicLandingPageTrackingDocument;
use Tests\TestCase;

class PublicLandingPageTrackingDocumentTest extends TestCase
{
    public function test_it_injects_the_google_ads_tag_when_utm_source_is_google(): void
    {
        $html = <<<'HTML'
<!doctype html>
<html>
<head><title>Catalog</title></head>
<body><h1>Products</h1></body>
</html>
HTML;

        $document = $this->tracking()->apply(
            $html,
            'google',
            'AW-16990837573/i9NRCNzf3PkcEMW27qU_',
            null,
        );

        $this->assertStringContainsString('https://www.googletagmanager.com/gtag/js?id=AW-16990837573', $document);
        $this->assertStringContainsString("gtag('config', 'AW-16990837573')", $document);
        $this->assertStringContainsString("'send_to': 'AW-16990837573/i9NRCNzf3PkcEMW27qU_'", $document);
        $this->assertStringNotContainsString('fbevents.js', $document);
    }

    public function test_it_injects_the_meta_pixel_when_utm_source_is_facebook(): void
    {
        $html = <<<'HTML'
<!doctype html>
<html>
<head><title>Catalog</title></head>
<body><h1>Products</h1></body>
</html>
HTML;

        $document = $this->tracking()->apply(
            $html,
            'facebook',
            null,
            '680344444359627',
        );

        $this->assertStringContainsString('https://connect.facebook.net/en_US/fbevents.js', $document);
        $this->assertStringContainsString("fbq('init', '680344444359627')", $document);
        $this->assertStringContainsString("fbq('track', 'PageView')", $document);
        $this->assertStringNotContainsString('googletagmanager.com', $document);
    }

    public function test_it_does_not_inject_pixels_without_a_matching_utm_source(): void
    {
        $html = <<<'HTML'
<!doctype html>
<html>
<head><title>Catalog</title></head>
<body><h1>Products</h1></body>
</html>
HTML;

        $document = $this->tracking()->apply(
            $html,
            'bing',
            'AW-16990837573/i9NRCNzf3PkcEMW27qU_',
            '680344444359627',
        );

        $this->assertStringNotContainsString('googletagmanager.com', $document);
        $this->assertStringNotContainsString('fbevents.js', $document);
    }

    public function test_it_does_not_inject_pixels_when_no_ids_are_configured(): void
    {
        $html = <<<'HTML'
<!doctype html>
<html>
<head><title>Catalog</title></head>
<body><h1>Products</h1></body>
</html>
HTML;

        $document = $this->tracking()->apply($html, 'google', null, null);

        $this->assertStringNotContainsString('googletagmanager.com', $document);
    }

    private function tracking(): PublicLandingPageTrackingDocument
    {
        return new PublicLandingPageTrackingDocument(new LandingPagePixelInjector);
    }
}
