<?php

namespace Tests\Unit;

use App\Campaigns\CampaignLandingPageText;
use App\DTOs\LandingPageAnalysis;
use App\Library\CampaignDecision\CampaignPerformanceBrief;
use App\Services\LandingPageAnalyzer;
use Illuminate\Support\Facades\Cache;
use Tests\TestCase;

class CampaignLandingPageTextTest extends TestCase
{
    protected function setUp(): void
    {
        parent::setUp();

        Cache::flush();
    }

    public function test_a_page_break_stores_the_landing_page_text_and_reuses_it(): void
    {
        $analyzer = $this->createMock(LandingPageAnalyzer::class);
        $analyzer->expects($this->once())
            ->method('analyze')
            ->with('https://example.com/landing', true)
            ->willReturn(new LandingPageAnalysis(
                url: 'https://example.com/landing',
                title: 'Lucos',
                description: 'Approve the change before it touches your code.',
                headings: ['Approve the change', 'See the plan'],
                text: 'Review every step before the code changes.',
                keywords: [],
            ));

        $store = new CampaignLandingPageText($analyzer);
        $snapshot = $this->pageBreakSnapshot();
        $stored = $store->fillIfPageIsTheBreak($snapshot);

        $page = $stored['creative_context']['landing_page'];
        $this->assertSame('Approve the change', $page['headings'][0]);
        $this->assertStringContainsString('Review every step', $page['text']);

        $store->fillIfPageIsTheBreak($snapshot);
        $this->assertSame(1, count($stored['creative_context']['landing_flow'] ?? []));
    }

    public function test_it_follows_onboarding_links_on_the_same_host(): void
    {
        $analyzer = $this->createMock(LandingPageAnalyzer::class);
        $analyzer->expects($this->exactly(2))
            ->method('analyze')
            ->willReturnOnConsecutiveCalls(
                new LandingPageAnalysis(
                    url: 'https://example.com/start',
                    title: 'Start',
                    description: '',
                    headings: ['Get answers, not links'],
                    text: 'Continue to search.',
                    keywords: [],
                    sameHostLinks: [['url' => 'https://example.com/onboarding/code', 'label' => 'Continue']],
                ),
                new LandingPageAnalysis(
                    url: 'https://example.com/onboarding/code',
                    title: 'Code',
                    description: '',
                    headings: ['Enter your code'],
                    text: 'Paste the code from the ad to finish signup.',
                    keywords: [],
                ),
            );

        $store = new CampaignLandingPageText($analyzer);
        $snapshot = $this->pageBreakSnapshot();
        $snapshot['creative_context']['landing_url'] = 'https://example.com/start';
        $stored = $store->fillIfPageIsTheBreak($snapshot);

        $this->assertCount(2, $stored['creative_context']['landing_flow']);
        $this->assertSame('Enter your code', $stored['creative_context']['landing_flow'][1]['headings'][0]);
    }

    public function test_an_auction_break_does_not_fetch_the_page(): void
    {
        $analyzer = $this->createMock(LandingPageAnalyzer::class);
        $analyzer->expects($this->never())->method('analyze');

        $snapshot = $this->pageBreakSnapshot();
        $snapshot['windows']['7d']['spend'] = 100;
        $snapshot['windows']['7d']['clicks'] = 40;
        $snapshot['windows']['7d']['ctr'] = 0.02;
        $snapshot['windows']['7d']['cpc'] = 2.5;

        $this->assertFalse(CampaignPerformanceBrief::pageIsTheBreak($snapshot));

        $stored = (new CampaignLandingPageText($analyzer))->fillIfPageIsTheBreak($snapshot);

        $this->assertNull($stored['creative_context']['landing_page']['text']);
    }

    public function test_a_javascript_shell_is_not_stored_as_page_text(): void
    {
        $analyzer = $this->createMock(LandingPageAnalyzer::class);
        $analyzer->expects($this->once())
            ->method('analyze')
            ->willReturn(new LandingPageAnalysis(
                url: 'https://example.com/landing',
                title: 'Lucos',
                description: '',
                headings: [],
                text: '',
                keywords: [],
            ));

        $stored = (new CampaignLandingPageText($analyzer))->remember([
            'landing_url' => 'https://example.com/landing',
            'landing_page' => ['title' => null, 'headings' => [], 'text' => null],
        ]);

        $this->assertNull($stored['landing_page']['text']);
        $this->assertFalse(Cache::has('campaign-landing-page:'.sha1('https://example.com/landing')));
    }

    public function test_a_fresh_creative_read_keeps_the_page_saved_on_the_hourly_run(): void
    {
        $store = new CampaignLandingPageText($this->createMock(LandingPageAnalyzer::class));
        $kept = $store->keepStoredPage(
            ['landing_url' => 'https://search.com/onboarding/landing', 'landing_page' => ['title' => null, 'headings' => [], 'text' => null]],
            ['landing_page' => [
                'title' => 'Sign in — Search.com',
                'headings' => ['Get answers, not links. Search smarter today.', 'Enter your code'],
                'text' => 'Continue with Google.',
            ]],
        );

        $this->assertSame('Sign in — Search.com', $kept['landing_page']['title']);
        $this->assertSame('Enter your code', $kept['landing_page']['headings'][1]);
    }

    /**
     * @return array<string, mixed>
     */
    private function pageBreakSnapshot(): array
    {
        return [
            'verdict' => 'learning',
            'campaign_profile' => ['objective' => 'OUTCOME_LEADS'],
            'creative_context' => [
                'landing_url' => 'https://example.com/landing?utm_source=meta&utm_campaign={{campaign.id}}',
                'landing_page' => ['title' => null, 'headings' => [], 'text' => null],
                'ads' => [[
                    'headline' => 'One wrong file change',
                    'primary_text' => 'You approve the change.',
                    'cta' => 'SEE_DETAILS',
                ]],
            ],
            'windows' => [
                '7d' => [
                    'spend' => 80,
                    'impressions' => 2000,
                    'clicks' => 40,
                    'ctr' => 0.02,
                    'cpc' => 2,
                    'conversions' => 0,
                ],
            ],
            'marketing_diagnosis' => ['primary_lever' => 'fix_landing_page'],
        ];
    }
}
