<?php

namespace Tests\Feature;

use App\Mcp\Servers\CampaignPerformanceServer;
use App\Mcp\Tools\Performance\CampaignHealth;
use App\Mcp\Tools\Performance\FindCampaign;
use App\Mcp\Tools\Performance\PortfolioSummary;
use App\Models\CampaignPerformanceSuggestion;
use App\Models\User;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Support\Facades\DB;
use Tests\Concerns\CreatesAdopsWhaleTables;
use Tests\TestCase;

class CampaignPerformanceMcpTest extends TestCase
{
    use CreatesAdopsWhaleTables;
    use RefreshDatabase;

    public function test_find_campaign_returns_matching_whale_rows(): void
    {
        $this->travelTo('2026-09-22 12:00:00');
        $this->createAdopsWhaleTables();
        $this->insertCampaign();

        $response = CampaignPerformanceServer::tool(FindCampaign::class, [
            'query' => 'Italy',
        ]);

        $response->assertOk();
        $response->assertSee('Italy packages');
        $response->assertSee('1201');
    }

    public function test_campaign_health_returns_a_verdict_without_calling_platforms(): void
    {
        $this->travelTo('2026-09-22 12:00:00');
        config(['campaign-performance.llm_enabled' => false]);
        $this->createAdopsWhaleTables();
        User::factory()->create();
        $this->insertCampaign();

        $response = CampaignPerformanceServer::tool(CampaignHealth::class, [
            'campaign_id' => '1201',
            'platform' => 'meta',
        ]);

        $response->assertOk();
        $response->assertSee('Italy packages');
        $response->assertSee('revenue_included');
        $response->assertSee('false');
        $response->assertSee('verdict');
        $response->assertSee('campaign_details');
        $response->assertSee('last_7_hours');
        $response->assertSee('outcome_window');
        $response->assertSee('act_111');
        $response->assertSee('"answer":', false);
        $response->assertSee('Reply with the answer field exactly.', false);
        $response->assertDontSee('Print implementation_plan', false);
    }

    public function test_campaign_health_includes_saved_status_and_ai_status(): void
    {
        $this->travelTo('2026-09-22 12:00:00');
        config(['campaign-performance.llm_enabled' => false]);
        $this->createAdopsWhaleTables();
        $user = User::factory()->create();
        $this->insertCampaign();
        CampaignPerformanceSuggestion::query()->create([
            'user_id' => $user->id,
            'platform' => 'meta',
            'external_campaign_id' => '1201',
            'status' => 'pause',
            'source' => 'adops',
            'reason' => 'Saved pause reason',
            'confidence' => 'medium',
            'snapshot' => ['ai_status' => 'watch'],
            'suggested_at' => now(),
        ]);

        $response = CampaignPerformanceServer::tool(CampaignHealth::class, [
            'campaign_id' => '1201',
            'platform' => 'meta',
        ]);

        $response->assertOk();
        $response->assertSee('saved_status');
        $response->assertSee('pause');
        $response->assertSee('watch');
        $response->assertSee('ACTIVE');
    }

    public function test_campaign_health_returns_the_saved_decision_text(): void
    {
        $this->travelTo('2026-09-22 12:00:00');
        config(['campaign-performance.llm_enabled' => false]);
        $this->createAdopsWhaleTables();
        $user = User::factory()->create();
        $this->insertCampaign();
        CampaignPerformanceSuggestion::query()->create([
            'user_id' => $user->id,
            'platform' => 'meta',
            'external_campaign_id' => '1201',
            'status' => 'pause',
            'source' => 'adops',
            'reason' => "Checked the last 7 days.\nImprove the creative.\n800 impressions produced 0 clicks.",
            'confidence' => 'medium',
            'snapshot' => [
                'ai_status' => 'pause',
                'decision_engine' => 'v2',
                'reason' => 'Pause after $12.10 spend with no clicks.',
                'marketing_diagnosis' => [
                    'primary_lever' => 'improve_creative',
                    'plan' => [
                        'Checked the last 7 days.',
                        'Improve the creative.',
                        '800 impressions produced 0 clicks.',
                    ],
                ],
            ],
            'suggested_at' => now(),
        ]);

        $response = CampaignPerformanceServer::tool(CampaignHealth::class, [
            'campaign_id' => '1201',
            'platform' => 'meta',
        ]);

        $response->assertOk();
        $response->assertSee('implementation_plan');
        // A pause verdict whose plan only said "improve the creative" would
        // leave the buyer still spending, so the pause step has to survive.
        $response->assertSee('- Pause the campaign and stop all spend.', false);
        $response->assertSee('"verdict":"pause"', false);
        $response->assertSee('Pause after $12.10 spend with no clicks.', false);
        $response->assertSee('stored_evaluation');
    }

    public function test_portfolio_summary_explains_when_analysis_has_not_run(): void
    {
        $this->createAdopsWhaleTables();

        $response = CampaignPerformanceServer::tool(PortfolioSummary::class, []);

        $response->assertOk();
        $response->assertSee('No hourly analysis yet');
    }

    public function test_google_find_does_not_pretend_ingest_exists(): void
    {
        $this->createAdopsWhaleTables();

        $response = CampaignPerformanceServer::tool(FindCampaign::class, [
            'query' => 'Italy',
            'platform' => 'google',
        ]);

        $response->assertOk();
        $response->assertSee('not ready');
    }

    private function insertCampaign(): void
    {
        $this->seedAdopsCampaignMeta('1201', 'Italy packages');
        DB::connection('whale')->table('arb_adops_stats_campaign_daily')->insert([
            'platform' => 'meta',
            'account_id' => 'act_111',
            'campaign_id' => '1201',
            'stat_date' => now()->toDateString(),
            'spend' => 12.10,
            'impressions' => 400,
            'clicks' => 10,
        ]);
    }
}
