<?php

namespace Tests\Feature;

use App\Campaigns\PerformanceVerdict;
use App\Models\CampaignPerformanceSuggestion;
use App\Models\User;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Support\Facades\Config;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Schema;
use Tests\Concerns\CreatesAdopsWhaleTables;
use Tests\TestCase;

class CampaignPerformanceWhaleMapTest extends TestCase
{
    use CreatesAdopsWhaleTables;
    use RefreshDatabase;

    protected function setUp(): void
    {
        parent::setUp();

        Config::set('campaign-performance.whale_enabled', true);
        Config::set('campaign-performance.llm_enabled', false);

        if (! Schema::connection('whale')->hasTable('arb_adops_campaign_performance')) {
            Schema::connection('whale')->create('arb_adops_campaign_performance', function (Blueprint $table): void {
                $table->unsignedBigInteger('id')->primary();
                $table->date('date');
                $table->string('campaign_id', 32);
                $table->unsignedInteger('clicks');
                $table->decimal('sum_cpc', 12, 4);
                $table->decimal('orders', 12, 4);
                $table->decimal('net_revenue', 12, 4);
                $table->json('debug_json')->nullable();
            });
        }
    }

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

        User::factory()->create();
        $externalId = '120251915605170683';

        $this->seedAdopsCampaign($externalId, 'Whale test', 6.0, 0);

        DB::connection('whale')->table('arb_adops_campaign_performance')->insert([
            'id' => 105,
            'date' => '2026-09-19',
            'campaign_id' => $externalId,
            'clicks' => 3,
            'sum_cpc' => 0.15,
            'orders' => 3,
            'net_revenue' => 89.44,
            'debug_json' => null,
        ]);

        Http::fake();

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

        $suggestion = CampaignPerformanceSuggestion::query()->first();

        $this->assertNotNull($suggestion);
        $this->assertSame(PerformanceVerdict::Continue->value, $suggestion->status);
        $this->assertTrue(data_get($suggestion->snapshot, 'affiliate.matched'));
        $this->assertStringContainsString('affiliate data', strtolower((string) $suggestion->reason));
    }
}
