<?php

namespace Tests\Feature;

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

class PublicCatalogLandingPageControllerTest extends TestCase
{
    use RefreshDatabase;

    public function test_guests_receive_completed_catalog_page_html_from_the_shared_public_route(): void
    {
        $page = $this->publicCatalogPage();

        $this->get($this->showUrl($page))
            ->assertOk()
            ->assertHeader('Content-Type', 'text/html; charset=UTF-8')
            ->assertSee('Office Depot catalog', false);
    }

    public function test_www_host_matches_the_canonical_publish_host(): void
    {
        $page = $this->publicCatalogPage();

        $this->get(route('public-prompt-landing-pages.show', [
            'domain' => 'www.attestpath.ai',
            'purpose' => 'catalog-benefits',
            'landing_page' => $page->id,
        ]))->assertOk();
    }

    public function test_returns_404_when_the_page_is_not_completed(): void
    {
        $page = $this->publicCatalogPage(overrides: [
            'status' => 'queued',
            'html' => null,
        ]);

        $this->get($this->showUrl($page))->assertNotFound();
    }

    public function test_returns_404_when_the_domain_does_not_match(): void
    {
        $page = $this->publicCatalogPage();

        $this->get(route('public-prompt-landing-pages.show', [
            'domain' => 'other.example.com',
            'purpose' => 'catalog-benefits',
            'landing_page' => $page->id,
        ]))->assertNotFound();
    }

    public function test_returns_404_when_the_purpose_does_not_match(): void
    {
        $page = $this->publicCatalogPage();

        $this->get(route('public-prompt-landing-pages.show', [
            'domain' => 'attestpath.ai',
            'purpose' => 'catalog-comparison',
            'landing_page' => $page->id,
        ]))->assertNotFound();
    }

    public function test_returns_404_when_the_generation_has_no_publish_website(): void
    {
        $generation = LandingPageGeneration::factory()
            ->catalog()
            ->create([
                'website_url' => null,
            ]);

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

        $this->get(route('public-prompt-landing-pages.show', [
            'domain' => 'attestpath.ai',
            'purpose' => 'catalog-benefits',
            'landing_page' => $page->id,
        ]))->assertNotFound();
    }

    public function test_returns_404_when_affiliate_tracking_is_not_configured(): void
    {
        $generation = LandingPageGeneration::factory()
            ->catalog()
            ->withPartnerWebsite()
            ->create([
                'website_url' => 'https://attestpath.ai',
            ]);

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

        $this->get(route('public-prompt-landing-pages.show', [
            'domain' => 'attestpath.ai',
            'purpose' => 'catalog-benefits',
            'landing_page' => $page->id,
        ]))->assertNotFound();
    }

    public function test_show_wraps_product_links_with_validclick_when_affiliate_tracking_is_configured(): void
    {
        $page = $this->publicCatalogPage(
            overrides: [
                'html' => '<section class="product-rows"><a class="row-cta" href="https://example.com/product">Shop</a></section>',
            ],
            generationOverrides: [
                'admedia_campaign_id' => '122609',
                'affiliate_key' => 'rateit_shop',
            ],
        );

        $this->get($this->showUrl($page).'?utm_source=google&utm_campaign=spring')
            ->assertOk()
            ->assertSee('click.validclick.net/rdr3.php', false)
            ->assertSee('aff_id=126664', false)
            ->assertSee('cid=122609', false)
            ->assertSee('subid=google_spring', false)
            ->assertSee('url=https%3A%2F%2Fexample.com%2Fproduct', false);
    }

    public function test_catalog_purpose_slugs_do_not_accept_lead_submissions(): void
    {
        $page = $this->publicCatalogPage();

        $this->postJson(route('public-prompt-landing-pages.leads.store', [
            'domain' => 'attestpath.ai',
            'purpose' => 'catalog-benefits',
            'landing_page' => $page->id,
        ]), ['email' => 'buyer@example.com'])
            ->assertNotFound();
    }

    public function test_show_injects_the_google_ads_tag_when_utm_source_is_google(): void
    {
        $page = $this->publicCatalogPage(generationOverrides: [
            'google_conversion_send_to' => 'AW-16990837573/i9NRCNzf3PkcEMW27qU_',
        ]);

        $this->get($this->showUrl($page).'?utm_source=google')
            ->assertOk()
            ->assertSee('https://www.googletagmanager.com/gtag/js?id=AW-16990837573', false)
            ->assertSee("gtag('config', 'AW-16990837573')", false)
            ->assertSee("gtag('event', 'conversion', window.__admediaCatalogGoogle)", false)
            ->assertSee('isCatalogProductCta', false)
            ->assertDontSee('fbevents.js', false);
    }

    public function test_show_injects_the_meta_pixel_when_utm_source_is_facebook(): void
    {
        $page = $this->publicCatalogPage(generationOverrides: [
            'meta_pixel_id' => '680344444359627',
            'brand_name' => 'OD',
        ]);

        $this->get($this->showUrl($page).'?utm_source=facebook')
            ->assertOk()
            ->assertSee('https://connect.facebook.net/en_US/fbevents.js', false)
            ->assertSee("fbq('init', '680344444359627')", false)
            ->assertSee('window.__admediaCatalogMetaLead = "ODLead"', false)
            ->assertSee("fbq('trackCustom', window.__admediaCatalogMetaLead)", false)
            ->assertSee('isCatalogProductCta', false)
            ->assertDontSee('googletagmanager.com', false);
    }

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

        $page = LandingPage::factory()
            ->for($generation, 'generation')
            ->completed()
            ->create(array_merge([
                'version' => LandingPageVersion::Benefits,
                'html' => '<section><h1>Office Depot catalog</h1></section>',
            ], $overrides));

        $generation->update([
            'published_landing_page_id' => $page->id,
            'published_at' => now(),
        ]);

        return $page->fresh(['generation']);
    }

    private function showUrl(LandingPage $page): string
    {
        $page->load('generation');

        return route('public-prompt-landing-pages.show', [
            'domain' => $page->generation->publicHost(),
            'purpose' => $page->purposeSlug(),
            'landing_page' => $page->id,
        ]);
    }
}
