<?php

namespace Tests\Unit\Services;

use App\Enums\LandingPageLayoutMode;
use App\Enums\LandingPageVersion;
use App\Models\LandingPage;
use App\Models\LandingPageGeneration;
use App\Models\User;
use App\Services\CatalogLandingPageAffiliateDocument;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Tests\TestCase;

class CatalogLandingPageAffiliateDocumentTest extends TestCase
{
    use RefreshDatabase;

    public function test_it_wraps_product_links_with_validclick_urls(): void
    {
        $page = $this->catalogPage([
            'admedia_campaign_id' => '122609',
            'affiliate_key' => 'rateit_shop',
        ], <<<'HTML'
<section class="product-rows">
    <article class="product-row">
        <a class="row-cta" href="https://example.com/product">Shop now</a>
    </article>
</section>
HTML);

        $html = app(CatalogLandingPageAffiliateDocument::class)->apply($page, 'google', 'spring');

        $this->assertStringContainsString('https://click.validclick.net/rdr3.php?', $html);
        $this->assertStringContainsString('aff_id=126664', $html);
        $this->assertStringContainsString('cid=122609', $html);
        $this->assertStringContainsString('subid=google_spring', $html);
        $this->assertStringContainsString('url=https%3A%2F%2Fexample.com%2Fproduct', $html);
    }

    public function test_it_leaves_html_unmodified_without_affiliate_tracking(): void
    {
        $page = $this->catalogPage([], <<<'HTML'
<section class="product-rows"><a class="row-cta" href="https://example.com/product">Shop now</a></section>
HTML);

        $html = app(CatalogLandingPageAffiliateDocument::class)->apply($page, 'google', 'spring');

        $this->assertStringContainsString('href="https://example.com/product"', $html);
        $this->assertStringNotContainsString('click.validclick.net', $html);
    }

    /**
     * @param  array<string, mixed>  $generationOverrides
     */
    private function catalogPage(array $generationOverrides, string $html): LandingPage
    {
        $generation = LandingPageGeneration::factory()
            ->catalog()
            ->withPartnerWebsite()
            ->for(User::factory())
            ->create(array_merge([
                'layout_mode' => LandingPageLayoutMode::Catalog,
            ], $generationOverrides));

        return LandingPage::factory()
            ->for($generation, 'generation')
            ->completed()
            ->create([
                'version' => LandingPageVersion::Benefits,
                'html' => $html,
            ])
            ->load('generation');
    }
}
