<?php

namespace Tests\Feature;

use App\Campaigns\Manager\CampaignSynchronizer;
use App\Models\Campaign;
use App\Models\CampaignPlatformDrift;
use App\Models\CampaignPlatformEntity;
use App\Models\CampaignSyncRun;
use App\Models\User;
use App\Services\GoogleAdsService;
use App\Services\LinkedIn\LinkedIn;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Http\Client\Request;
use Illuminate\Support\Facades\Http;
use InvalidArgumentException;
use Mockery;
use Tests\TestCase;

/**
 * The campaign manager keeps its own record of what each platform says a
 * campaign looks like, and notices when that changes between reads - which is
 * how an edit made in Ads Manager, Google Ads or Campaign Manager reaches us.
 */
class CampaignManagerSyncTest extends TestCase
{
    use RefreshDatabase;

    private User $user;

    /** @var array{campaign: array<string, mixed>, adsets: list<array<string, mixed>>, ads: list<array<string, mixed>>, fail: bool} */
    private array $meta = ['campaign' => [], 'adsets' => [], 'ads' => [], 'fail' => false];

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

        config([
            'platforms.meta.token' => 'test-token',
            'platforms.meta.mcp.enabled' => false,
            'platforms.guardrails.allowed_ad_accounts' => ['meta:*'],
            'platforms.guardrails.paused' => false,
        ]);

        $this->user = User::factory()->create();

        $this->meta['campaign'] = [
            'id' => '120252047635070626',
            'name' => 'Winter Sale',
            'status' => 'ACTIVE',
            'effective_status' => 'ACTIVE',
            'objective' => 'OUTCOME_TRAFFIC',
            'account_id' => '111',
        ];
        $this->meta['adsets'] = [
            ['id' => 'adset-1', 'name' => 'US mobile', 'status' => 'ACTIVE', 'daily_budget' => '2500', 'optimization_goal' => 'LINK_CLICKS'],
        ];
        $this->meta['ads'] = [
            ['id' => 'ad-1', 'name' => 'Winter Sale - ad 1', 'status' => 'ACTIVE', 'effective_status' => 'ACTIVE', 'adset_id' => 'adset-1', 'creative' => ['id' => 'cr-1', 'title' => 'Everything reduced']],
        ];

        Http::fake(function (Request $request) {
            if ($this->meta['fail']) {
                return Http::response(['error' => ['message' => 'Service temporarily unavailable', 'code' => 2]], 500);
            }

            $path = (string) parse_url($request->url(), PHP_URL_PATH);

            return match (true) {
                str_ends_with($path, '/adsets') => Http::response(['data' => $this->meta['adsets']]),
                str_ends_with($path, '/ads') => Http::response(['data' => $this->meta['ads']]),
                default => Http::response($this->meta['campaign']),
            };
        });
    }

    private function campaign(array $attributes = []): Campaign
    {
        return Campaign::create([
            'user_id' => $this->user->id,
            'name' => 'Winter Sale',
            'platform' => 'meta',
            'status' => 'published',
            'objective' => 'OUTCOME_TRAFFIC',
            'ad_account_id' => 'act_111',
            'currency' => 'USD',
            'budget' => 25,
            'budget_mode' => 'daily',
            'external_campaign_id' => '120252047635070626',
            ...$attributes,
        ]);
    }

    private function sync(Campaign $campaign): CampaignSyncRun
    {
        return app(CampaignSynchronizer::class)->sync($campaign, 'manual', 'User#1 campaign manager');
    }

    public function test_the_first_read_is_a_baseline_without_drift(): void
    {
        $campaign = $this->campaign();

        $run = $this->sync($campaign);

        $this->assertSame(CampaignSyncRun::Succeeded, $run->status, (string) $run->error);
        $this->assertTrue($run->complete);
        $this->assertSame(3, $run->entity_count);
        $this->assertSame(0, $run->drift_count);
        $this->assertSame(0, CampaignPlatformDrift::count());

        $adSet = $campaign->platformEntities()->where('external_id', 'adset-1')->sole();
        $this->assertSame('ad_set', $adSet->entity_type);
        $this->assertSame('campaign', $adSet->parent_type);
        $this->assertEquals(25, $adSet->settings['daily_budget']);
        $this->assertSame('Everything reduced', $campaign->platformEntities()->where('external_id', 'ad-1')->sole()->settings['headline']);
    }

    public function test_meta_ad_sets_are_read_with_the_settings_ads_manager_can_change(): void
    {
        $this->meta['adsets'][0] += ['destination_type' => 'WEBSITE', 'pacing_type' => ['standard'], 'daily_spend_cap' => '4000', 'effective_status' => 'ACTIVE'];

        $this->sync($campaign = $this->campaign());

        Http::assertSent(fn (Request $request): bool => str_ends_with((string) parse_url($request->url(), PHP_URL_PATH), '/adsets')
            && str_contains(urldecode($request->url()), 'frequency_control_specs'));

        $settings = $campaign->platformEntities()->where('external_id', 'adset-1')->sole()->settings;
        $this->assertSame('WEBSITE', $settings['destination_type']);
        $this->assertSame(['standard'], $settings['pacing_type']);
        $this->assertEquals(40, $settings['daily_spend_cap']);
    }

    public function test_a_budget_changed_in_ads_manager_is_recorded_as_drift(): void
    {
        $campaign = $this->campaign();
        $this->sync($campaign);

        $this->meta['adsets'][0]['daily_budget'] = '3000';
        $run = $this->sync($campaign);

        $this->assertSame(1, $run->drift_count);
        $drift = CampaignPlatformDrift::sole();
        $this->assertSame(CampaignPlatformDrift::Changed, $drift->kind);
        $this->assertSame('settings.daily_budget', $drift->field);
        $this->assertEquals(25, $drift->before);
        $this->assertEquals(30, $drift->after);
        $this->assertSame('adset-1', $drift->entity->external_id);
    }

    public function test_an_unchanged_read_records_no_drift(): void
    {
        $campaign = $this->campaign();
        $this->sync($campaign);

        $run = $this->sync($campaign);

        $this->assertSame(0, $run->drift_count);
        $this->assertSame(0, CampaignPlatformDrift::count());
    }

    public function test_a_failed_read_keeps_the_last_snapshot(): void
    {
        $campaign = $this->campaign();
        $this->sync($campaign);

        $this->meta['fail'] = true;
        $run = $this->sync($campaign);

        $this->assertSame(CampaignSyncRun::Failed, $run->status);
        $this->assertNotEmpty($run->error);
        $this->assertSame(3, $campaign->platformEntities()->present()->count());
        $this->assertSame(0, CampaignPlatformDrift::count());
    }

    public function test_an_object_deleted_on_the_platform_is_removed_and_can_come_back(): void
    {
        $campaign = $this->campaign();
        $this->sync($campaign);
        $ads = $this->meta['ads'];

        $this->meta['ads'] = [];
        $this->sync($campaign);

        $ad = $campaign->platformEntities()->where('external_id', 'ad-1')->sole();
        $this->assertNotNull($ad->removed_at);
        $this->assertSame(CampaignPlatformDrift::Removed, CampaignPlatformDrift::sole()->kind);

        $this->meta['ads'] = $ads;
        $this->sync($campaign);

        $this->assertNull($ad->refresh()->removed_at);
        $this->assertSame(CampaignPlatformDrift::Restored, CampaignPlatformDrift::latest('id')->first()->kind);
    }

    public function test_a_new_object_after_the_baseline_is_recorded_as_added(): void
    {
        $campaign = $this->campaign();
        $this->sync($campaign);

        $this->meta['adsets'][] = ['id' => 'adset-2', 'name' => 'UK test', 'status' => 'PAUSED'];
        $run = $this->sync($campaign);

        $this->assertSame(1, $run->drift_count);
        $this->assertSame(CampaignPlatformDrift::Added, CampaignPlatformDrift::sole()->kind);
    }

    public function test_a_full_page_does_not_mark_unseen_objects_removed(): void
    {
        $campaign = $this->campaign();
        $this->sync($campaign);

        $this->meta['ads'] = array_map(fn (int $i): array => [
            'id' => 'other-'.$i, 'name' => 'Ad '.$i, 'status' => 'ACTIVE', 'adset_id' => 'adset-1',
        ], range(1, 50));
        $run = $this->sync($campaign);

        $this->assertSame(CampaignSyncRun::Partial, $run->status);
        $this->assertFalse($run->complete);
        $this->assertNotEmpty($run->gaps);
        $this->assertNull($campaign->platformEntities()->where('external_id', 'ad-1')->sole()->removed_at);
        $this->assertSame(0, CampaignPlatformDrift::where('kind', CampaignPlatformDrift::Removed)->count());
    }

    public function test_a_campaign_on_a_platform_without_a_reader_is_refused(): void
    {
        $campaign = $this->campaign(['platform' => 'tiktok']);

        $this->expectException(InvalidArgumentException::class);

        $this->sync($campaign);
    }

    public function test_a_google_campaign_is_read_as_ad_groups_and_ads(): void
    {
        config([
            'services.google_ads.refresh_token' => 'a-refresh-token',
            'services.google_ads.customer_id' => '3460855874',
        ]);

        $profile = ['id' => '987', 'name' => 'Search - brand', 'status' => 'ENABLED', 'primary_status' => 'ELIGIBLE', 'daily_budget' => 50.0];
        $structure = [
            'channel_type' => 'SEARCH',
            'ad_groups' => [['id' => '11', 'name' => 'Brand', 'status' => 'ENABLED', 'cpc_bid' => 1.5, 'keywords' => ['acme']]],
            'ads' => [['id' => '21', 'ad_group_id' => '11', 'status' => 'ENABLED', 'approval_status' => 'APPROVED', 'headline' => 'Acme']],
            'asset_groups' => [],
        ];

        $google = Mockery::mock(GoogleAdsService::class);
        $google->shouldReceive('readManagerCriteria')->andReturn([]);
        $google->shouldReceive('readManagerAudiences')->andReturn([]);
        $google->shouldReceive('readCampaignProfile')->andReturnUsing(function () use (&$profile): array {
            return $profile;
        });
        $google->shouldReceive('readCampaignStructure')->andReturn($structure);
        $this->app->instance(GoogleAdsService::class, $google);

        $campaign = $this->campaign(['platform' => 'google', 'ad_account_id' => '3460855874', 'external_campaign_id' => '987']);
        $run = $this->sync($campaign);

        $this->assertSame(CampaignSyncRun::Succeeded, $run->status, (string) $run->error);
        $this->assertSame(['ad', 'ad_group', 'campaign'], $campaign->platformEntities()->orderBy('entity_type')->pluck('entity_type')->all());
        $this->assertSame('APPROVED', $campaign->platformEntities()->where('entity_type', 'ad')->sole()->effective_status);

        $profile['daily_budget'] = 80.0;
        $this->sync($campaign);

        $this->assertSame('settings.daily_budget', CampaignPlatformDrift::sole()->field);
    }

    public function test_a_linkedin_campaign_is_read_with_its_group_and_creatives(): void
    {
        $linkedin = Mockery::mock(LinkedIn::class);
        $linkedin->shouldReceive('campaignConversions')->andReturn([]);
        $linkedin->shouldReceive('on')->andReturnSelf();
        $linkedin->shouldReceive('campaign')->andReturn([
            'id' => 555, 'name' => 'Lead gen', 'status' => 'ACTIVE', 'campaignGroup' => 'urn:li:sponsoredCampaignGroup:44',
            'dailyBudget' => ['amount' => '100', 'currencyCode' => 'USD'], 'version' => ['versionTag' => '3'],
        ]);
        $linkedin->shouldReceive('campaignGroup')->andReturn(['id' => 44, 'name' => 'Q4', 'status' => 'ACTIVE']);
        $linkedin->shouldReceive('creatives')->andReturn([
            'elements' => [['id' => 'urn:li:sponsoredCreative:77', 'campaign' => 'urn:li:sponsoredCampaign:555', 'intendedStatus' => 'ACTIVE', 'isServing' => true]],
            'next_page_token' => null,
        ]);
        $this->app->instance(LinkedIn::class, $linkedin);

        $campaign = $this->campaign(['platform' => 'linkedin', 'ad_account_id' => 'urn:li:sponsoredAccount:999', 'external_campaign_id' => '555']);
        $run = $this->sync($campaign);

        $this->assertSame(CampaignSyncRun::Succeeded, $run->status, (string) $run->error);

        $linkedInCampaign = $campaign->platformEntities()->where('entity_type', 'campaign')->sole();
        $this->assertSame('campaign_group', $linkedInCampaign->parent_type);
        $this->assertSame('44', $linkedInCampaign->parent_external_id);
        $this->assertArrayNotHasKey('version', $linkedInCampaign->settings);
        $this->assertSame('SERVING', $campaign->platformEntities()->where('entity_type', 'creative')->sole()->effective_status);
    }

    public function test_the_command_reads_stale_managed_campaigns(): void
    {
        $stale = $this->campaign();
        CampaignSyncRun::factory()->for($stale)->create(['platform' => 'meta', 'started_at' => now()->subHours(3), 'finished_at' => now()->subHours(3)]);
        $fresh = $this->campaign(['name' => 'Fresh']);
        CampaignSyncRun::factory()->for($fresh)->create(['platform' => 'meta']);
        $this->campaign(['name' => 'Draft', 'status' => 'draft', 'external_campaign_id' => null]);

        $this->artisan('campaigns:sync-structure')->assertSuccessful();

        $this->assertSame(2, $stale->syncRuns()->count());
        $this->assertSame('scheduled', $stale->latestSyncRun()->first()->trigger);
        $this->assertSame(1, $fresh->syncRuns()->count());
    }

    public function test_entity_and_run_factories_build_valid_rows(): void
    {
        $this->assertSame(CampaignSyncRun::Failed, CampaignSyncRun::factory()->failed()->create()->status);
        $this->assertSame('ad_set', CampaignPlatformEntity::factory()->create()->entity_type);
    }
}
