<?php

namespace Tests\Feature;

use App\Campaigns\PerformanceVerdict;
use App\Campaigns\PerformanceWindows;
use App\Models\CampaignPerformanceVerdictLog;
use App\Models\User;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Support\Facades\Http;
use Tests\Concerns\CreatesAdopsWhaleTables;
use Tests\TestCase;

class CampaignPerformanceVerdictTest extends TestCase
{
    use CreatesAdopsWhaleTables;
    use RefreshDatabase;

    public function test_daily_monitor_appends_a_verdict_log_with_all_five_windows(): 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);

        Http::fake();

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

        $log = CampaignPerformanceVerdictLog::query()->first();
        $this->assertNotNull($log);
        $this->assertSame('daily', $log->run_type);
        $this->assertSame(['3h', '5h', '7h', '3d', '7d'], array_keys($log->windows ?? []));
        $this->assertSame(PerformanceVerdict::Stop->value, $log->final_verdict);
        $this->assertNull($log->hourly_verdict);
    }

    public function test_hourly_monitor_appends_intraday_windows_and_hourly_verdict(): 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, 0, 7, 0);

        foreach (range(0, 6) as $offset) {
            $this->seedAdopsHourly(
                '1201',
                now()->copy()->startOfHour()->subHours(6 - $offset),
                4.0,
                0,
                40,
            );
        }

        Http::fake();

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

        $log = CampaignPerformanceVerdictLog::query()->first();
        $this->assertNotNull($log);
        $this->assertSame('hourly', $log->run_type);
        $this->assertSame(PerformanceWindows::hourWindowKeys(), array_keys($log->windows ?? []));
        $this->assertIsArray($log->hourly_verdict);
        $this->assertSame(PerformanceVerdict::Stop->value, $log->final_verdict);
    }

    public function test_analysis_windows_are_hardcoded_without_env(): void
    {
        $this->assertSame(
            ['3h', '5h', '7h', '3d', '7d'],
            array_keys(PerformanceWindows::analysis()),
        );
    }
}
