<?php

namespace Tests\Feature;

use App\Models\CampaignPerformanceSuggestion;
use App\Models\User;
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\Concerns\CreatesAdopsWhaleTables;
use Tests\TestCase;

class CampaignPerformanceMapTest extends TestCase
{
    use CreatesAdopsWhaleTables;
    use RefreshDatabase;

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

        User::factory()->create();
        $this->seedAdopsCampaign('1201', 'Italy packages', 6.0, 0, 7, 0);

        Http::fake();

        $this->artisan('campaigns:monitor-adops', ['--daily' => true])->assertSuccessful();

        $row = CampaignPerformanceSuggestion::query()->first();
        $this->assertNotNull($row);
        $this->assertSame('stop', $row->status);
        $this->assertSame('php', $row->source);
        $this->assertSame('pending', $row->action_state);
        $this->assertSame('stop', $row->snapshot['final_verdict'] ?? null);
        $this->assertSame('unknown', $row->snapshot['trend'] ?? null);
        $this->assertSame(0, $row->snapshot['last_7_hours']['hours'] ?? null);
        Http::assertNothingSent();
    }

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

        User::factory()->create();
        $this->seedAdopsCampaignMeta('1201', 'Italy packages');
        $this->seedAdopsDaily('1201', '2026-09-10', 20.00, 10, 2000);
        $this->seedAdopsDaily('1201', '2026-09-20', 20.00, 20, 2000);

        Http::fake();

        $this->artisan('campaigns:monitor-adops', ['--daily' => true])->assertSuccessful();

        $row = CampaignPerformanceSuggestion::query()->first();
        $this->assertNotNull($row);
        $this->assertSame('improving', $row->snapshot['trend']);
        $this->assertSame(40.0, (float) $row->snapshot['lifetime']['spend']);
        $this->assertSame('continue', $row->status);
    }

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

        User::factory()->create();
        $this->seedAdopsCampaign('1201', 'Italy packages', 10.0, 2, 7, 0);

        foreach ([
            ['2026-09-22 08:00:00', 1.00, 1, 10],
            ['2026-09-22 09:00:00', 2.00, 2, 20],
            ['2026-09-22 10:00:00', 3.00, 3, 30],
            ['2026-09-22 11:00:00', 4.00, 4, 40],
            ['2026-09-22 12:00:00', 5.00, 5, 50],
        ] as [$hour, $spend, $clicks, $impressions]) {
            $this->seedAdopsHourly('1201', $hour, $spend, $clicks, $impressions);
        }

        Http::fake();

        $this->artisan('campaigns:monitor-adops', ['--hourly' => true])->assertSuccessful();

        $row = CampaignPerformanceSuggestion::query()->first();
        $this->assertNotNull($row);
        $this->assertSame('continue', $row->status);
        $this->assertSame('pending', $row->action_state);
        $this->assertSame(15.0, (float) $row->snapshot['last_7_hours']['spend']);
        $this->assertGreaterThanOrEqual(5, (int) $row->snapshot['last_7_hours']['hours']);
        $this->assertSame(15, (int) $row->snapshot['last_7_hours']['clicks']);
        $this->assertSame(70.0, (float) $row->snapshot['last_7_days']['spend']);
        $this->assertSame('hourly', $row->snapshot['verdicts']['run_type'] ?? null);
    }

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

        User::factory()->create();
        $this->seedAdopsCampaignMeta('1201', 'Italy packages');
        $this->seedAdopsDaily('1201', '2026-09-20', 20.00, 4, 800);
        $this->seedAdopsDaily('1201', '2026-08-01', 99.00, 9, 900);
        Schema::connection('whale')->dropIfExists('arb_adops_campaign_performance');
        Schema::connection('whale')->create('arb_adops_campaign_performance', function (Blueprint $table): void {
            $table->date('date');
            $table->string('campaign_id');
            $table->unsignedInteger('clicks')->default(0);
            $table->decimal('sum_cpc', 12, 4)->default(0);
            $table->decimal('orders', 12, 4)->default(0);
            $table->decimal('net_revenue', 12, 4)->default(0);
        });
        DB::connection('whale')->table('arb_adops_campaign_performance')->insert([
            'date' => '2026-09-20',
            'campaign_id' => '1201',
            'clicks' => 4,
            'sum_cpc' => 5,
            'orders' => 2,
            'net_revenue' => 50,
        ]);

        Http::fake();

        $this->artisan('campaigns:monitor-adops', ['--daily' => true])->assertSuccessful();

        $row = CampaignPerformanceSuggestion::query()->first();
        $history = $row?->snapshot['daily_history'] ?? null;
        $day = collect($history['rows'] ?? [])->firstWhere('date', '2026-09-20');

        $this->assertIsArray($history);
        $this->assertSame(30, $history['expected_days']);
        $this->assertSame('2026-08-24', $history['from']);
        $this->assertNotContains('2026-08-01', array_column($history['rows'], 'date'));
        $this->assertEquals(20, $day['spend']);
        $this->assertEquals(4, $day['clicks']);
        $this->assertEquals(2, $day['orders']);
        $this->assertEquals(50, $day['revenue']);
        Http::assertNothingSent();
    }
}
