<?php

namespace Tests\Feature;

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

class CampaignPerformanceAdopsMonitorTest extends TestCase
{
    use CreatesAdopsWhaleTables;
    use RefreshDatabase;

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

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

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

        $row = CampaignPerformanceSuggestion::query()->first();
        $this->assertNotNull($row);
        $this->assertSame('meta', $row->platform);
        $this->assertSame('1201', $row->external_campaign_id);
        $this->assertSame('pending', $row->action_state);
        $this->assertSame('whale_adops', $row->snapshot['data_source'] ?? null);
        $this->assertFalse($row->snapshot['revenue_included'] ?? true);
        $this->assertSame('Italy packages', $row->snapshot['campaign'] ?? null);
        $this->assertContains($row->status, ['pause', 'stop', 'action_required', 'no_action', 'continue']);
    }

    public function test_monitor_skips_when_adops_is_disabled(): void
    {
        config(['campaign-performance.adops_enabled' => false]);

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

        $this->assertSame(0, CampaignPerformanceSuggestion::query()->count());
    }

    public function test_google_is_skipped_until_adops_ingest_exists(): void
    {
        $this->createAdopsWhaleTables();
        User::factory()->create();

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

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

        $this->createAdopsWhaleTables();
        User::factory()->create();

        $schema = Schema::connection('whale');
        $schema->create('arb_adops_stats_daily_202609', function (Blueprint $table): void {
            $table->string('platform', 24);
            $table->string('account_id');
            $table->string('campaign_id');
            $table->date('stat_date');
            $table->decimal('spend', 12, 2)->default(0);
            $table->unsignedBigInteger('impressions')->default(0);
            $table->unsignedBigInteger('clicks')->default(0);
        });

        DB::connection('whale')->table('arb_adops_stats_daily_202609')->insert([
            'platform' => 'meta',
            'account_id' => 'act_111',
            'campaign_id' => '1201',
            'stat_date' => '2026-09-22',
            'spend' => 6.0,
            'impressions' => 100,
            'clicks' => 0,
        ]);

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

        $row = CampaignPerformanceSuggestion::query()->first();
        $this->assertNotNull($row);
        $this->assertSame('1201', $row->external_campaign_id);
        $this->assertSame('whale_adops', $row->snapshot['data_source'] ?? null);
    }

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

        $this->wipeAdopsWhaleRows();
        $user = User::factory()->create();
        Campaign::create([
            'user_id' => $user->id,
            'name' => 'Local only',
            'platform' => 'meta',
            'status' => 'published',
            'budget' => 20,
            'ad_account_id' => 'act_111',
            'external_campaign_id' => '7777',
        ]);

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

        $this->assertSame(0, CampaignPerformanceSuggestion::query()->count());
    }

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

        $this->wipeAdopsWhaleRows();
        User::factory()->create();
        $this->seedAdopsAd('8888', 'Ads only campaign');

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

        $row = CampaignPerformanceSuggestion::query()->first();
        $this->assertNotNull($row);
        $this->assertSame('8888', $row->external_campaign_id);
        $this->assertSame('Ads only campaign', $row->snapshot['campaign'] ?? null);
    }

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

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

        DB::connection('whale')->table('arb_adops_sync_status')->update([
            'last_success_at' => now()->subHours(5),
            'status' => 'ok',
            'error' => null,
        ]);

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

        $row = CampaignPerformanceSuggestion::query()->first();
        $this->assertNotNull($row);
        $this->assertFalse($row->snapshot['sync_failed'] ?? true);
        $this->assertNull($row->snapshot['sync_error']);
    }

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

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

        DB::connection('whale')->table('arb_adops_sync_status')->update([
            'status' => 'failed',
            'error' => 'Meta API error 80004',
        ]);

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

        $row = CampaignPerformanceSuggestion::query()->first();
        $this->assertNotNull($row);
        $this->assertTrue($row->snapshot['sync_failed'] ?? false);
        $this->assertSame('Meta API error 80004', $row->snapshot['sync_error'] ?? null);
    }
}
