<?php

namespace Tests\Feature;

use App\Models\CampaignDecision;
use App\Models\CampaignPerformanceSuggestion;
use App\Models\User;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Tests\TestCase;

class BackfillReviewDetailsCommandTest extends TestCase
{
    use RefreshDatabase;

    public function test_it_fills_missing_creative_ids_image_prompts_and_the_landing_page_prompt(): void
    {
        $user = User::factory()->create();
        $suggestion = CampaignPerformanceSuggestion::query()->create([
            'user_id' => $user->id,
            'platform' => 'meta',
            'external_campaign_id' => '120251936608840626',
            'status' => 'pause',
            'source' => 'llm',
            'reason' => 'Change the picture and the page.',
            'snapshot' => $this->snapshot(),
            'suggested_at' => now(),
        ]);
        $decision = CampaignDecision::query()->create([
            'user_id' => $user->id,
            'platform' => 'meta',
            'account_id' => 'act_1',
            'external_campaign_id' => '120251936608840626',
            'campaign_name' => 'Lucos retargeting',
            'evaluated_at' => now(),
            'verdict' => 'pause',
            'confidence' => 0.8,
            'recommended_action' => 'pause',
            'reason' => 'Change the picture and the page.',
            'snapshot_json' => $this->snapshot(),
        ]);
        CampaignPerformanceSuggestion::query()->create([
            'user_id' => $user->id,
            'platform' => 'meta',
            'external_campaign_id' => '999',
            'status' => 'pause',
            'source' => 'llm',
            'reason' => 'Leave this campaign alone.',
            'snapshot' => [
                'review' => [
                    'creatives' => [[
                        'ad_id' => 'other',
                        'current_headline' => 'Other ad',
                        'action' => 'keep',
                        'why' => 'It is working.',
                    ]],
                ],
            ],
            'suggested_at' => now(),
        ]);

        $this->artisan('campaigns:backfill-review-details', ['--campaign' => '120251936608840626'])
            ->expectsOutputToContain('Updated 1 suggestion(s) and 1 decision(s).')
            ->assertSuccessful();

        $suggestion->refresh();
        $decision->refresh();
        $creative = $suggestion->snapshot['review']['creatives'][0];
        $kept = $suggestion->snapshot['review']['creatives'][1];

        $this->assertSame('925887686918149', $creative['creative_id']);
        $this->assertStringContainsString('Approve Code Changes Before They Happen', $creative['image_prompt']);
        $this->assertStringContainsString('Meta feed still', $creative['image_prompt']);
        $this->assertStringContainsString('Exact on-image line', $creative['image_prompt']);
        $this->assertStringContainsString('The studio makes the still', $creative['image_prompt']);
        $this->assertStringNotContainsString('4.06', $creative['image_prompt']);
        $this->assertArrayNotHasKey('image_prompt', $kept);
        $this->assertStringContainsString('offsite sign-up page', $suggestion->snapshot['review']['landing']['prompt']);
        $this->assertStringContainsString('Not a Meta instant lead form', $suggestion->snapshot['review']['landing']['prompt']);
        $this->assertSame('925887686918149', $decision->snapshot_json['review']['creatives'][0]['creative_id']);
        $this->assertNull(data_get(
            CampaignPerformanceSuggestion::query()->where('external_campaign_id', '999')->first()?->snapshot,
            'review.creatives.0.image_prompt',
        ));
    }

    public function test_a_dry_run_does_not_write_and_a_second_run_leaves_existing_prompts(): void
    {
        $user = User::factory()->create();
        $suggestion = CampaignPerformanceSuggestion::query()->create([
            'user_id' => $user->id,
            'platform' => 'meta',
            'external_campaign_id' => '120251936608840626',
            'status' => 'pause',
            'source' => 'llm',
            'reason' => 'Change the picture and the page.',
            'snapshot' => $this->snapshot(),
            'suggested_at' => now(),
        ]);

        $this->artisan('campaigns:backfill-review-details', ['--dry-run' => true])
            ->expectsOutputToContain('Would update 1 suggestion(s) and 0 decision(s).')
            ->assertSuccessful();

        $suggestion->refresh();
        $this->assertSame('', (string) data_get($suggestion->snapshot, 'review.creatives.0.image_prompt'));

        $this->artisan('campaigns:backfill-review-details')->assertSuccessful();
        $suggestion->refresh();
        $written = $suggestion->snapshot['review']['creatives'][0]['image_prompt'];

        $this->artisan('campaigns:backfill-review-details')
            ->expectsOutputToContain('Updated 0 suggestion(s) and 0 decision(s).')
            ->assertSuccessful();

        $suggestion->refresh();
        $this->assertSame($written, $suggestion->snapshot['review']['creatives'][0]['image_prompt']);
    }

    /**
     * @return array<string, mixed>
     */
    private function snapshot(): array
    {
        return [
            'campaign_goals' => [
                'objective' => 'OUTCOME_LEADS',
                'optimization_goals' => ['OFFSITE_CONVERSIONS'],
            ],
            'creative_context' => [
                'ads' => [[
                    'ad_id' => '120252007591870626',
                    'headline' => 'One Wrong File Change Can Cost You 20 Minutes',
                    'images' => [[
                        'ad_id' => '120252007591870626',
                        'creative_id' => '925887686918149',
                    ]],
                ]],
            ],
            'review' => [
                'creatives' => [
                    [
                        'ad_id' => '120252007591870626',
                        'current_headline' => 'One Wrong File Change Can Cost You 20 Minutes',
                        'action' => 'change',
                        'why' => 'The picture shows the old way of working. It drew no clicks on $4.06.',
                        'replacement_headline' => 'Approve Code Changes Before They Happen',
                        'replacement_primary_text' => 'See what Lucos plans to change before it touches your code.',
                    ],
                    [
                        'ad_id' => '120252007038090626',
                        'current_headline' => 'Lucos vs. Copilot vs. Cursor',
                        'action' => 'keep',
                        'why' => 'The comparison is earning clicks.',
                    ],
                ],
                'landing' => [
                    'problem' => 'The route to sign-up is unclear.',
                    'flow' => 'Lead with the benefit, then the workflow, then the sign-up.',
                    'headline' => 'Build and Review Code With Lucos',
                    'section' => 'Explore agents and models in one workspace.',
                    'cta' => 'Sign Up for Lucos',
                    'content' => 'Build and Review Code With Lucos',
                ],
            ],
        ];
    }
}
