<?php

namespace Tests\Unit;

use App\Campaigns\CampaignCreativeContext;
use App\DTOs\LandingPageAnalysis;
use App\Models\AdCopy;
use App\Models\Asset;
use App\Models\Brief;
use App\Models\Campaign;
use App\Models\CampaignAd;
use App\Models\CampaignCreative;
use App\Models\Creative;
use App\Models\User;
use App\Services\LandingPageAnalyzer;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Schema;
use Tests\TestCase;

class CampaignCreativeContextTest extends TestCase
{
    use RefreshDatabase;

    public function test_it_includes_the_landing_page_and_creative_copy(): void
    {
        $user = User::factory()->create();
        $brief = Brief::query()->create([
            'user_id' => $user->id,
            'landing_url' => 'https://example.com/mac',
            'page_analysis' => [
                'url' => 'https://example.com/mac',
                'title' => 'Search Browser for Mac',
                'description' => 'A browser that finds what you need.',
                'headings' => ['Download for Mac'],
                'text' => 'Install the browser and search the web.',
                'keywords' => ['browser'],
            ],
        ]);
        $campaign = Campaign::query()->create([
            'user_id' => $user->id,
            'brief_id' => $brief->id,
            'name' => 'Search Browser',
            'platform' => 'meta',
            'objective' => 'traffic',
            'landing_url' => 'https://example.com/mac',
            'external_campaign_id' => '120249356799650510',
        ]);
        $creative = Creative::query()->create([
            'user_id' => $user->id,
            'type' => 'image',
            'source' => 'upload',
            'title' => 'Mac browser still',
        ]);
        $copy = AdCopy::query()->create([
            'user_id' => $user->id,
            'creative_id' => $creative->id,
            'primary_text' => 'Search faster on your Mac.',
            'headline' => 'Browser for Mac',
            'description' => 'Free download.',
            'cta' => 'DOWNLOAD',
        ]);
        CampaignCreative::query()->create([
            'campaign_id' => $campaign->id,
            'creative_id' => $creative->id,
            'ad_copy_id' => $copy->id,
        ]);
        CampaignAd::query()->create([
            'campaign_id' => $campaign->id,
            'headline' => 'Get the Mac browser',
            'primary_text' => 'Built for Mac search.',
            'cta' => 'LEARN_MORE',
        ]);

        $context = (new CampaignCreativeContext)->forExternal('meta', '120249356799650510');

        $this->assertTrue($context['found']);
        $this->assertSame('https://example.com/mac', $context['landing_url']);
        $this->assertSame('Search Browser for Mac', $context['landing_page']['title']);
        $this->assertSame('Browser for Mac', $context['creatives'][0]['headline']);
        $this->assertSame((string) $creative->id, $context['creatives'][0]['creative_id']);
        $this->assertSame('Get the Mac browser', $context['ads'][0]['headline']);
    }

    public function test_it_reports_when_the_campaign_was_not_created_here(): void
    {
        $context = (new CampaignCreativeContext)->forExternal('meta', '120249356799650510');

        $this->assertFalse($context['found']);
    }

    public function test_it_reads_whale_ad_copy_when_the_campaign_was_not_created_here(): void
    {
        Schema::connection('whale')->create('arb_adops_ads', function (Blueprint $table): void {
            $table->string('platform');
            $table->string('campaign_id');
            $table->string('ad_id');
            $table->string('name')->nullable();
            $table->string('creative_id')->nullable();
            $table->string('final_url')->nullable();
            $table->string('effective_status')->nullable();
        });
        Schema::connection('whale')->create('arb_adops_creatives', function (Blueprint $table): void {
            $table->string('platform');
            $table->string('creative_id');
            $table->text('primary_text')->nullable();
            $table->text('headlines')->nullable();
            $table->string('cta')->nullable();
            $table->string('landing_url')->nullable();
        });
        DB::connection('whale')->table('arb_adops_ads')->insert([
            'platform' => 'meta',
            'campaign_id' => '120251936608840626',
            'ad_id' => '120252007591870626',
            'name' => 'New Leads Ad',
            'creative_id' => '925887686918149',
            'final_url' => 'https://lucos.com/landing?utm_source=meta',
            'effective_status' => 'ACTIVE',
        ]);
        DB::connection('whale')->table('arb_adops_creatives')->insert([
            'platform' => 'meta',
            'creative_id' => '925887686918149',
            'primary_text' => 'Lucos reviews every step before it touches your code.',
            'headlines' => json_encode([['text' => 'One Wrong File Change Can Cost You 20 Minutes']]),
            'cta' => 'SEE_DETAILS',
            'landing_url' => 'https://lucos.com/landing',
        ]);

        $context = (new CampaignCreativeContext)->forExternal('meta', '120251936608840626');

        $this->assertTrue($context['found']);
        $this->assertSame('whale', $context['source']);
        $this->assertSame('https://lucos.com/landing?utm_source=meta', $context['landing_url']);
        $this->assertSame('One Wrong File Change Can Cost You 20 Minutes', $context['ads'][0]['headline']);
        $this->assertSame('925887686918149', $context['ads'][0]['creative_id']);
        $this->assertNull($context['landing_page']['text']);
    }

    public function test_a_whale_campaign_reads_the_public_landing_page_when_the_brief_has_no_text(): void
    {
        config(['campaign-performance.read_landing_pages' => true]);
        $this->app->instance(LandingPageAnalyzer::class, new class extends LandingPageAnalyzer
        {
            public function analyze(string $url, bool $renderShell = false): LandingPageAnalysis
            {
                return new LandingPageAnalysis(
                    url: $url,
                    title: 'Lucos',
                    description: 'Reviews every file change.',
                    headings: ['See the risk before you merge'],
                    text: 'The page opens on a logo and a single button.',
                    keywords: ['lucos'],
                );
            }
        });

        Schema::connection('whale')->create('arb_adops_ads', function (Blueprint $table): void {
            $table->string('platform');
            $table->string('campaign_id');
            $table->string('ad_id');
            $table->string('final_url')->nullable();
            $table->string('creative_id')->nullable();
        });
        DB::connection('whale')->table('arb_adops_ads')->insert([
            'platform' => 'meta',
            'campaign_id' => '120251727706600626',
            'ad_id' => '1',
            'creative_id' => null,
            'final_url' => 'https://lucos.com/landing?utm_source=meta',
        ]);

        $context = (new CampaignCreativeContext)->forExternal('meta', '120251727706600626');

        $this->assertSame('https://lucos.com/landing', $context['landing_url'] ? strtok((string) $context['landing_url'], '?') : null);
        $this->assertSame('The page opens on a logo and a single button.', $context['landing_page']['text']);
        $this->assertSame('See the risk before you merge', $context['landing_page']['headings'][0]);
    }

    public function test_a_whale_campaign_keeps_every_ad_and_both_delivery_windows(): void
    {
        Schema::connection('whale')->create('arb_adops_ads', function (Blueprint $table): void {
            $table->string('platform');
            $table->string('campaign_id');
            $table->string('ad_id');
            $table->string('name')->nullable();
            $table->string('creative_id')->nullable();
            $table->string('final_url')->nullable();
            $table->string('effective_status')->nullable();
        });
        Schema::connection('whale')->create('arb_adops_creatives', function (Blueprint $table): void {
            $table->string('platform');
            $table->string('creative_id');
            $table->text('primary_text')->nullable();
            $table->text('headlines')->nullable();
            $table->text('description')->nullable();
            $table->string('cta')->nullable();
        });
        $stats = 'arb_adops_stats_daily_'.now()->format('Ym');
        Schema::connection('whale')->create($stats, function (Blueprint $table): void {
            $table->string('platform');
            $table->string('campaign_id');
            $table->string('ad_id');
            $table->date('stat_date');
            $table->decimal('spend', 12, 2)->default(0);
            $table->integer('impressions')->default(0);
            $table->integer('clicks')->default(0);
        });

        foreach ([
            ['ad_id' => 'ad-weak', 'creative_id' => 'c1', 'headline' => 'Weak headline', 'primary_text' => 'Weak primary text.'],
            ['ad_id' => 'ad-strong', 'creative_id' => 'c2', 'headline' => 'Strong headline', 'primary_text' => 'Strong primary text.'],
        ] as $ad) {
            DB::connection('whale')->table('arb_adops_ads')->insert([
                'platform' => 'meta',
                'campaign_id' => 'camp-1',
                'ad_id' => $ad['ad_id'],
                'name' => $ad['headline'],
                'creative_id' => $ad['creative_id'],
                'final_url' => 'https://example.com/offer',
                'effective_status' => 'ACTIVE',
            ]);
            DB::connection('whale')->table('arb_adops_creatives')->insert([
                'platform' => 'meta',
                'creative_id' => $ad['creative_id'],
                'primary_text' => $ad['primary_text'],
                'headlines' => json_encode([['text' => $ad['headline']]]),
                'description' => 'Offer description.',
                'cta' => 'LEARN_MORE',
            ]);
        }

        DB::connection('whale')->table($stats)->insert([
            [
                'platform' => 'meta',
                'campaign_id' => 'camp-1',
                'ad_id' => 'ad-weak',
                'stat_date' => now()->subDays(2)->toDateString(),
                'spend' => 12.5,
                'impressions' => 1000,
                'clicks' => 2,
            ],
            [
                'platform' => 'meta',
                'campaign_id' => 'camp-1',
                'ad_id' => 'ad-strong',
                'stat_date' => now()->subDays(20)->toDateString(),
                'spend' => 40,
                'impressions' => 2000,
                'clicks' => 80,
            ],
        ]);

        $context = (new CampaignCreativeContext)->forExternal('meta', 'camp-1');
        $byId = collect($context['ads'])->keyBy('ad_id');

        $this->assertCount(2, $context['ads']);
        $this->assertSame('Weak headline', $byId['ad-weak']['headline']);
        $this->assertSame('Weak primary text.', $byId['ad-weak']['primary_text']);
        $this->assertSame(12.5, $byId['ad-weak']['last_7_days']['spend']);
        $this->assertSame(12.5, $byId['ad-weak']['last_30_days']['spend']);
        $this->assertArrayNotHasKey('last_7_days', $byId['ad-strong']);
        $this->assertSame(40.0, $byId['ad-strong']['last_30_days']['spend']);
        $this->assertSame('ad-weak', $context['ad_performance'][0]['ad_id']);
    }

    public function test_an_empty_local_campaign_uses_the_whale_ad_and_landing_url(): void
    {
        config(['campaign-performance.read_landing_pages' => false]);
        $user = User::factory()->create();
        Campaign::query()->create([
            'user_id' => $user->id,
            'name' => 'New Meta Campaign',
            'platform' => 'meta',
            'objective' => 'traffic',
            'external_campaign_id' => '120251606607900626',
        ]);
        Schema::connection('whale')->create('arb_adops_ads', function (Blueprint $table): void {
            $table->string('platform');
            $table->string('campaign_id');
            $table->string('ad_id');
            $table->string('name')->nullable();
            $table->string('creative_id')->nullable();
            $table->string('final_url')->nullable();
            $table->string('effective_status')->nullable();
        });
        Schema::connection('whale')->create('arb_adops_creatives', function (Blueprint $table): void {
            $table->string('platform');
            $table->string('creative_id');
            $table->text('primary_text')->nullable();
            $table->text('headlines')->nullable();
            $table->string('cta')->nullable();
            $table->string('landing_url')->nullable();
        });
        DB::connection('whale')->table('arb_adops_ads')->insert([
            'platform' => 'meta',
            'campaign_id' => '120251606607900626',
            'ad_id' => '120251606607860626',
            'name' => 'Attestpath-SCO-2 – Copy',
            'creative_id' => '964558893364455',
            'final_url' => 'https://attestpath.ai/landing/soc-2?utm_source=meta',
            'effective_status' => 'ACTIVE',
        ]);
        DB::connection('whale')->table('arb_adops_creatives')->insert([
            'platform' => 'meta',
            'creative_id' => '964558893364455',
            'primary_text' => 'See how Attestpath covers SOC 2.',
            'headlines' => json_encode([['text' => 'SOC 2 without the scramble']]),
            'cta' => 'LEARN_MORE',
            'landing_url' => 'https://attestpath.ai/landing/soc-2',
        ]);

        $context = (new CampaignCreativeContext)->forExternal('meta', '120251606607900626');

        $this->assertSame('whale', $context['source']);
        $this->assertSame('SOC 2 without the scramble', $context['ads'][0]['headline']);
        $this->assertSame('https://attestpath.ai/landing/soc-2?utm_source=meta', $context['landing_url']);
    }

    public function test_a_whale_campaign_includes_still_images_and_the_scraped_offer(): void
    {
        config(['campaign-performance.read_landing_pages' => true]);
        Http::fake(function ($request) {
            $path = (string) parse_url($request->url(), PHP_URL_PATH);

            if ($path === '/' || $path === '') {
                return Http::response(<<<'HTML'
                    <html><head><title>Acme outfitter</title></head><body>
                        <h1>Acme outfitter</h1>
                        <p>We sell trail gear for long weekends.</p>
                    </body></html>
                HTML);
            }

            if (str_contains($path, '/about')) {
                return Http::response(<<<'HTML'
                    <html><head><title>About Acme</title></head><body>
                        <h1>About Acme</h1>
                        <p>A family company since 1998.</p>
                    </body></html>
                HTML);
            }

            if (str_contains($path, '/pricing')) {
                return Http::response(<<<'HTML'
                    <html><head><title>Plans</title></head><body>
                        <h1>Plans</h1>
                        <p>The yearly plan is $120.</p>
                    </body></html>
                HTML);
            }

            return Http::response(<<<'HTML'
                <html><head>
                    <title>Trail shoes</title>
                    <meta name="description" content="Lightweight trail shoes.">
                </head><body>
                    <h1>Trail shoes</h1>
                    <h3>Free shipping</h3>
                    <p>Cushioned trail running shoes for marathon distance. Price $89.00.</p>
                    <a href="/buy">Buy now</a>
                    <a href="/about">Our story</a>
                    <a href="/pricing">See plans</a>
                    <a href="/privacy">Privacy policy</a>
                    <a href="https://other.example/deal">Elsewhere</a>
                </body></html>
            HTML);
        });
        Schema::connection('whale')->create('arb_adops_ads', function (Blueprint $table): void {
            $table->string('platform');
            $table->string('campaign_id');
            $table->string('ad_id');
            $table->string('creative_id')->nullable();
            $table->string('final_url')->nullable();
        });
        Schema::connection('whale')->create('arb_adops_creatives', function (Blueprint $table): void {
            $table->string('platform');
            $table->string('creative_id');
            $table->string('type')->nullable();
            $table->text('headlines')->nullable();
            $table->text('primary_text')->nullable();
            $table->text('image_urls')->nullable();
            $table->text('thumbnail_url')->nullable();
            $table->string('landing_url')->nullable();
        });
        DB::connection('whale')->table('arb_adops_ads')->insert([
            [
                'platform' => 'meta',
                'campaign_id' => 'camp-images',
                'ad_id' => 'ad-image',
                'creative_id' => 'cr-image',
                'final_url' => 'https://example.com/shoes',
            ],
            [
                'platform' => 'meta',
                'campaign_id' => 'camp-images',
                'ad_id' => 'ad-video',
                'creative_id' => 'cr-video',
                'final_url' => 'https://example.com/shoes',
            ],
        ]);
        DB::connection('whale')->table('arb_adops_creatives')->insert([
            [
                'platform' => 'meta',
                'creative_id' => 'cr-image',
                'type' => 'image',
                'headlines' => json_encode([['text' => 'Trail shoes']]),
                'primary_text' => 'Run farther.',
                'image_urls' => json_encode([
                    'https://cdn.example/shoe.jpg',
                    'https://cdn.example/clip.mp4',
                ]),
                'thumbnail_url' => null,
                'landing_url' => 'https://example.com/shoes',
            ],
            [
                'platform' => 'meta',
                'creative_id' => 'cr-video',
                'type' => 'video',
                'headlines' => json_encode([['text' => 'Watch the trail']]),
                'primary_text' => 'See the shoe move.',
                'image_urls' => json_encode(['https://cdn.example/full.mp4']),
                'thumbnail_url' => 'https://cdn.example/poster.jpg',
                'landing_url' => 'https://example.com/shoes',
            ],
        ]);

        $context = (new CampaignCreativeContext)->forExternal('meta', 'camp-images');
        $images = collect($context['images']);

        $this->assertSame('https://cdn.example/shoe.jpg', $images->firstWhere('kind', 'image')['url']);
        $this->assertSame('ad-image', $images->firstWhere('kind', 'image')['ad_id']);
        $this->assertSame('cr-image', $images->firstWhere('kind', 'image')['creative_id']);
        $this->assertSame('https://cdn.example/poster.jpg', $images->firstWhere('kind', 'poster')['url']);
        $this->assertNull($images->first(fn (array $image): bool => str_contains((string) ($image['url'] ?? ''), '.mp4')));
        $this->assertSame('Buy now', $context['landing_page']['calls_to_action'][0]);
        $this->assertNotContains('Privacy policy', $context['landing_page']['calls_to_action']);
        $this->assertContains('$89.00', $context['landing_page']['prices']);
        $this->assertSame('Free shipping', $context['landing_page']['subheadings'][0]);
        $this->assertStringContainsString('marathon distance', $context['landing_page']['text']);
        $pages = collect($context['website']['pages']);
        $this->assertSame('example.com', $context['website']['host']);
        $this->assertTrue($pages->contains(fn (array $page): bool => str_contains((string) $page['text'], 'trail gear')));
        $this->assertTrue($pages->contains(fn (array $page): bool => str_contains((string) $page['text'], 'family company since 1998')));
        $this->assertTrue($pages->contains(fn (array $page): bool => str_contains((string) $page['text'], 'yearly plan')));
        $this->assertFalse($pages->contains(fn (array $page): bool => str_contains((string) $page['url'], 'privacy')));
        $this->assertFalse($pages->contains(fn (array $page): bool => str_contains((string) $page['url'], 'other.example')));
    }

    public function test_a_local_image_is_included_and_a_video_file_is_not(): void
    {
        config(['campaign-performance.read_landing_pages' => false]);
        $user = User::factory()->create();
        $campaign = Campaign::query()->create([
            'user_id' => $user->id,
            'name' => 'Shoes',
            'platform' => 'meta',
            'objective' => 'sales',
            'external_campaign_id' => 'local-images',
        ]);
        $image = Asset::query()->create([
            'kind' => 'image',
            'source' => 'upload',
            'disk' => 'local',
            'path' => 'creatives/shoe.jpg',
            'mime' => 'image/jpeg',
        ]);
        $video = Asset::query()->create([
            'kind' => 'video',
            'source' => 'upload',
            'disk' => 'local',
            'path' => 'creatives/clip.mp4',
            'mime' => 'video/mp4',
        ]);
        CampaignAd::query()->create([
            'campaign_id' => $campaign->id,
            'asset_id' => $image->id,
            'headline' => 'Trail shoes',
            'primary_text' => 'Run farther.',
            'cta' => 'SHOP_NOW',
            'external_ad_id' => 'ad-local',
        ]);
        CampaignAd::query()->create([
            'campaign_id' => $campaign->id,
            'asset_id' => $video->id,
            'headline' => 'Watch the trail',
            'primary_text' => 'See the shoe move.',
            'cta' => 'WATCH_MORE',
            'external_ad_id' => 'ad-video',
        ]);

        $context = (new CampaignCreativeContext)->forExternal('meta', 'local-images');

        $this->assertCount(1, $context['images']);
        $this->assertSame('creatives/shoe.jpg', $context['images'][0]['path']);
        $this->assertSame('ad-local', $context['images'][0]['ad_id']);
        $this->assertSame('image', $context['images'][0]['kind']);
    }

    public function test_whale_ad_windows_include_prior_week_frequency_and_quality_when_on_file(): void
    {
        config(['campaign-performance.read_landing_pages' => false]);
        Schema::connection('whale')->create('arb_adops_ads', function (Blueprint $table): void {
            $table->string('platform');
            $table->string('campaign_id');
            $table->string('ad_id');
            $table->string('name')->nullable();
            $table->string('creative_id')->nullable();
            $table->string('final_url')->nullable();
            $table->string('effective_status')->nullable();
        });
        Schema::connection('whale')->create('arb_adops_creatives', function (Blueprint $table): void {
            $table->string('platform');
            $table->string('creative_id');
            $table->text('primary_text')->nullable();
            $table->text('headlines')->nullable();
            $table->string('cta')->nullable();
        });
        $stats = 'arb_adops_stats_daily_'.now()->format('Ym');
        Schema::connection('whale')->create($stats, function (Blueprint $table): void {
            $table->string('platform');
            $table->string('campaign_id');
            $table->string('ad_id');
            $table->date('stat_date');
            $table->decimal('spend', 12, 2)->default(0);
            $table->integer('impressions')->default(0);
            $table->integer('clicks')->default(0);
            $table->decimal('frequency', 8, 4)->nullable();
            $table->integer('landing_page_views')->nullable();
        });
        $quality = 'arb_adops_quality_daily_'.now()->format('Ym');
        Schema::connection('whale')->create($quality, function (Blueprint $table): void {
            $table->string('platform');
            $table->string('account_id')->nullable();
            $table->string('campaign_id');
            $table->string('entity_level');
            $table->string('entity_id');
            $table->date('stat_date');
            $table->string('metric');
            $table->string('value');
        });

        DB::connection('whale')->table('arb_adops_ads')->insert([
            'platform' => 'meta',
            'campaign_id' => 'camp-quality',
            'ad_id' => 'ad-ranked',
            'name' => 'Ranked ad',
            'creative_id' => 'cr-1',
            'final_url' => 'https://example.com/offer',
            'effective_status' => 'ACTIVE',
        ]);
        DB::connection('whale')->table('arb_adops_creatives')->insert([
            'platform' => 'meta',
            'creative_id' => 'cr-1',
            'primary_text' => 'Offer text.',
            'headlines' => json_encode([['text' => 'Offer headline']]),
            'cta' => 'SIGN_UP',
        ]);
        DB::connection('whale')->table($stats)->insert([
            [
                'platform' => 'meta',
                'campaign_id' => 'camp-quality',
                'ad_id' => 'ad-ranked',
                'stat_date' => now()->subDays(2)->toDateString(),
                'spend' => 20,
                'impressions' => 1000,
                'clicks' => 20,
                'frequency' => 1.8,
                'landing_page_views' => 12,
            ],
            [
                'platform' => 'meta',
                'campaign_id' => 'camp-quality',
                'ad_id' => 'ad-ranked',
                'stat_date' => now()->subDays(10)->toDateString(),
                'spend' => 18,
                'impressions' => 900,
                'clicks' => 36,
                'frequency' => 1.2,
                'landing_page_views' => 20,
            ],
        ]);
        DB::connection('whale')->table($quality)->insert([
            'platform' => 'meta',
            'account_id' => 'act-1',
            'campaign_id' => 'camp-quality',
            'entity_level' => 'ad',
            'entity_id' => 'ad-ranked',
            'stat_date' => now()->subDays(1)->toDateString(),
            'metric' => 'quality_ranking',
            'value' => 'AVERAGE',
        ]);

        $context = (new CampaignCreativeContext)->forExternal('meta', 'camp-quality');
        $ad = collect($context['ads'])->firstWhere('ad_id', 'ad-ranked');

        $this->assertSame(20.0, $ad['last_7_days']['spend']);
        $this->assertSame(1.8, $ad['last_7_days']['frequency']);
        $this->assertSame(12, $ad['last_7_days']['landing_page_views']);
        $this->assertSame(18.0, $ad['previous_7_days']['spend']);
        $this->assertSame('AVERAGE', $ad['quality_ranking']);
    }

    public function test_ad_windows_ignore_campaign_grain_rows(): void
    {
        config(['campaign-performance.read_landing_pages' => false]);
        Schema::connection('whale')->create('arb_adops_ads', function (Blueprint $table): void {
            $table->string('platform');
            $table->string('campaign_id');
            $table->string('ad_id');
            $table->string('name')->nullable();
            $table->string('creative_id')->nullable();
            $table->string('final_url')->nullable();
            $table->string('effective_status')->nullable();
        });
        Schema::connection('whale')->create('arb_adops_creatives', function (Blueprint $table): void {
            $table->string('platform');
            $table->string('creative_id');
            $table->text('primary_text')->nullable();
            $table->text('headlines')->nullable();
        });
        $stats = 'arb_adops_stats_daily_'.now()->format('Ym');
        Schema::connection('whale')->create($stats, function (Blueprint $table): void {
            $table->string('platform');
            $table->string('campaign_id');
            $table->string('ad_id')->nullable();
            $table->string('entity_level')->nullable();
            $table->date('stat_date');
            $table->decimal('spend', 12, 2)->default(0);
            $table->integer('impressions')->default(0);
            $table->integer('clicks')->default(0);
            $table->integer('link_clicks')->nullable();
        });

        DB::connection('whale')->table('arb_adops_ads')->insert([
            'platform' => 'meta',
            'campaign_id' => 'camp-grain',
            'ad_id' => 'ad-live',
            'name' => 'Live ad',
            'creative_id' => 'cr-live',
            'final_url' => 'https://example.com/offer',
            'effective_status' => 'ACTIVE',
        ]);
        DB::connection('whale')->table('arb_adops_creatives')->insert([
            'platform' => 'meta',
            'creative_id' => 'cr-live',
            'primary_text' => 'Offer text.',
            'headlines' => json_encode([['text' => 'Offer']]),
        ]);
        DB::connection('whale')->table($stats)->insert([
            [
                'platform' => 'meta',
                'campaign_id' => 'camp-grain',
                'ad_id' => 'ad-live',
                'entity_level' => 'campaign',
                'stat_date' => now()->subDays(1)->toDateString(),
                'spend' => 80,
                'impressions' => 8000,
                'clicks' => 80,
                'link_clicks' => 80,
            ],
            [
                'platform' => 'meta',
                'campaign_id' => 'camp-grain',
                'ad_id' => 'ad-live',
                'entity_level' => 'ad',
                'stat_date' => now()->subDays(1)->toDateString(),
                'spend' => 12.4,
                'impressions' => 900,
                'clicks' => 30,
                'link_clicks' => 18,
            ],
        ]);

        $context = (new CampaignCreativeContext)->forExternal('meta', 'camp-grain');
        $ad = collect($context['ads'])->firstWhere('ad_id', 'ad-live');

        $this->assertSame(12.4, $ad['last_7_days']['spend']);
        $this->assertSame(18, $ad['last_7_days']['link_clicks']);
        $this->assertEqualsWithDelta(18 / 900, $ad['last_7_days']['ctr'], 0.0001);
    }
}
