<?php

namespace Tests\Feature;

use App\Campaigns\Manager\CampaignSynchronizer;
use App\Campaigns\Manager\Editing\EditCapabilities;
use App\Campaigns\Manager\Editing\EditRefused;
use App\Campaigns\Manager\Editing\EntityEditor;
use App\Livewire\CampaignManager\EditEntity;
use App\Models\Campaign;
use App\Models\CampaignEntityEdit;
use App\Models\CampaignPlatformDrift;
use App\Models\CampaignPlatformEntity;
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 Illuminate\Validation\ValidationException;
use Livewire\Livewire;
use Mockery;
use Tests\TestCase;

/**
 * Bid strategies changed from the campaign manager, with the amount each one
 * reads: Meta's bid, Google's CPA and ROAS targets, LinkedIn's unit cost.
 */
class CampaignManagerBidStrategyTest extends TestCase
{
    use RefreshDatabase;

    private User $user;

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

    /** @var list<array{id: string, fields: array<string, mixed>}> */
    private array $writes = [];

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

        config([
            'platforms.meta.token' => 'test-token',
            'platforms.meta.mcp.enabled' => false,
            'platforms.guardrails.allowed_ad_accounts' => ['meta:*', 'google:*', 'linkedin:*'],
            'platforms.guardrails.paused' => false,
            'platforms.guardrails.change_cooldown_seconds' => 0,
            'platforms.guardrails.max_changes_per_day' => 50,
            'platforms.guardrails.budget_ceiling_currency' => 'USD',
            'platforms.guardrails.max_daily_budget' => 500,
            'campaign-manager.edit_platforms' => ['meta', 'google', 'linkedin'],
            'campaign-manager.edit_categories' => ['name', 'budget', 'bid', 'bid_strategy'],
            'services.google_ads.refresh_token' => 'token',
            'services.google_ads.customer_id' => '3460855874',
        ]);

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

        $this->meta['campaign'] = [
            'id' => '120252047635070626', 'name' => 'Winter Sale', 'status' => 'ACTIVE',
            'effective_status' => 'ACTIVE', 'objective' => 'OUTCOME_SALES', 'account_id' => '111',
        ];
        $this->meta['adsets'] = [
            ['id' => '2001', 'name' => 'US mobile', 'status' => 'ACTIVE', 'daily_budget' => '2500', 'bid_strategy' => 'LOWEST_COST_WITHOUT_CAP'],
        ];

        Http::fake(function (Request $request) {
            $path = (string) parse_url($request->url(), PHP_URL_PATH);

            if ($request->method() === 'POST') {
                $id = basename($path);
                $fields = array_diff_key($request->data(), ['access_token' => true]);
                $this->writes[] = ['id' => $id, 'fields' => $fields];

                if ($id === $this->meta['campaign']['id']) {
                    $this->meta['campaign'] = [...$this->meta['campaign'], ...$fields];
                }

                foreach ($this->meta['adsets'] as $i => $row) {
                    if ($row['id'] === $id) {
                        $this->meta['adsets'][$i] = [...$row, ...$fields];

                        // As Meta does: highest volume has no bid.
                        if (($fields['bid_strategy'] ?? null) === 'LOWEST_COST_WITHOUT_CAP') {
                            unset($this->meta['adsets'][$i]['bid_amount']);
                        }
                    }
                }

                return Http::response(['success' => true]);
            }

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

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

        app(CampaignSynchronizer::class)->sync($campaign);

        return $campaign;
    }

    private function entity(Campaign $campaign, string $externalId): CampaignPlatformEntity
    {
        return $campaign->platformEntities()->where('external_id', $externalId)->sole();
    }

    private function editor(): EntityEditor
    {
        return app(EntityEditor::class);
    }

    private function capabilities(): EditCapabilities
    {
        return app(EditCapabilities::class);
    }

    /** @param  array<string, mixed>  $values */
    private function assertRejected(Campaign $campaign, CampaignPlatformEntity $entity, array $values, string $field, string $message): void
    {
        try {
            $this->editor()->propose($campaign, $entity, $this->user, $values);
            $this->fail('Accepted '.json_encode($values));
        } catch (ValidationException $exception) {
            $this->assertStringContainsString($message, $exception->errors()[$field][0] ?? '');
        }
    }

    // ------------------------------------------------------------------ Meta

    public function test_a_meta_ad_set_moves_to_bid_cap_with_its_first_bid(): void
    {
        $campaign = $this->campaign();
        $adSet = $this->entity($campaign, '2001');

        $this->assertSame(['name', 'daily_budget', 'bid_strategy', 'bid_amount', 'pacing_type'], $this->capabilities()->editableFields($adSet));
        $this->assertRejected($campaign, $adSet, ['bid_strategy' => 'LOWEST_COST_WITH_BID_CAP', 'bid_amount' => ''], 'bid_strategy', 'Bid cap needs a bid');
        $this->assertRejected($campaign, $adSet, ['bid_strategy' => 'LOWEST_COST_WITH_MIN_ROAS'], 'bid_strategy', 'invalid');

        $edit = $this->editor()->propose($campaign, $adSet, $this->user, ['bid_strategy' => 'LOWEST_COST_WITH_BID_CAP', 'bid_amount' => '3.50']);

        $this->assertEquals([
            'bid_strategy' => ['before' => 'LOWEST_COST_WITHOUT_CAP', 'after' => 'LOWEST_COST_WITH_BID_CAP'],
            'bid_amount' => ['before' => null, 'after' => 3.5],
        ], $edit->changes);

        $notes = implode(' ', $this->capabilities()->confirmations($adSet, $edit->changes));
        $this->assertStringContainsString('from Highest volume (no cap) to Bid cap', $notes);
        $this->assertStringContainsString('With the bid at 3.50 USD, delivery can slow or stop', $notes);

        try {
            $this->editor()->apply($edit, $this->user);
            $this->fail('A strategy change went out without being acknowledged.');
        } catch (EditRefused $refused) {
            $this->assertStringContainsString('needs to be acknowledged', $refused->getMessage());
        }

        $edit = $this->editor()->apply($edit->refresh(), $this->user, acknowledged: true);

        $this->assertSame(CampaignEntityEdit::Applied, $edit->state, (string) $edit->error);
        $this->assertEquals([['id' => '2001', 'fields' => ['bid_strategy' => 'LOWEST_COST_WITH_BID_CAP', 'bid_amount' => '350']]], $this->writes);
        $this->assertSame('LOWEST_COST_WITH_BID_CAP', EditCapabilities::current($adSet->refresh(), 'bid_strategy'));
    }

    public function test_moving_to_highest_volume_leaves_the_bid_out(): void
    {
        $this->meta['adsets'][0] = [...$this->meta['adsets'][0], 'bid_strategy' => 'COST_CAP', 'bid_amount' => '400'];
        $campaign = $this->campaign();
        $adSet = $this->entity($campaign, '2001');

        $edit = $this->editor()->propose($campaign, $adSet, $this->user, ['bid_strategy' => 'LOWEST_COST_WITHOUT_CAP', 'bid_amount' => '9.00']);

        $this->assertSame(['bid_strategy'], array_keys($edit->changes));
        $this->assertStringContainsString('has no cap', implode(' ', $this->capabilities()->confirmations($adSet, $edit->changes)));

        $edit = $this->editor()->apply($edit, $this->user, acknowledged: true);

        $this->assertEquals([['id' => '2001', 'fields' => ['bid_strategy' => 'LOWEST_COST_WITHOUT_CAP']]], $this->writes);

        // Meta dropped the bid itself; that is read as part of this change, not someone else's.
        $drift = CampaignPlatformDrift::query()->where('campaign_platform_entity_id', $adSet->id)->where('field', 'settings.bid_amount')->sole();
        $this->assertNull($drift->after);
        $this->assertTrue(EditCapabilities::matchesDrift($edit, $drift));
        $this->assertSame('—', EditCapabilities::display($adSet->refresh(), 'bid_amount', $drift->after));
        $this->assertSame('Highest volume (no cap)', EditCapabilities::display($adSet, 'bid_strategy', 'LOWEST_COST_WITHOUT_CAP'));
    }

    public function test_under_a_campaign_budget_the_strategy_is_set_on_the_campaign(): void
    {
        $this->meta['campaign'] = [...$this->meta['campaign'], 'daily_budget' => '10000', 'bid_strategy' => 'LOWEST_COST_WITHOUT_CAP'];
        $this->meta['adsets'][0] = ['id' => '2001', 'name' => 'US mobile', 'status' => 'ACTIVE', 'bid_strategy' => 'LOWEST_COST_WITHOUT_CAP'];
        $campaign = $this->campaign();
        $root = $this->entity($campaign, '120252047635070626');
        $adSet = $this->entity($campaign, '2001');

        $this->assertNotContains('bid_strategy', $this->capabilities()->editableFields($adSet));
        $this->assertStringContainsString('set on the campaign', $this->capabilities()->lockedFields($adSet)['bid_strategy']);
        $this->assertContains('bid_strategy', $this->capabilities()->editableFields($root));

        // A cap there needs a bid on every ad set, which is not set from here.
        $this->assertRejected($campaign, $root, ['bid_strategy' => 'COST_CAP'], 'bid_strategy', '1 ad set has none');

        $this->meta['adsets'][0]['bid_amount'] = '500';
        app(CampaignSynchronizer::class)->sync($campaign);

        $edit = $this->editor()->propose($campaign, $root->refresh(), $this->user, ['bid_strategy' => 'COST_CAP']);
        $this->assertStringContainsString('every ad set', implode(' ', $this->capabilities()->confirmations($root, $edit->changes)));

        $this->assertSame(CampaignEntityEdit::Applied, $this->editor()->apply($edit, $this->user, acknowledged: true)->state);
        $this->assertEquals(['bid_strategy' => 'COST_CAP'], $this->writes[0]['fields']);
    }

    public function test_a_roas_goal_and_a_switched_off_category_are_not_offered(): void
    {
        $this->meta['adsets'][0]['bid_strategy'] = 'LOWEST_COST_WITH_MIN_ROAS';
        $campaign = $this->campaign();
        $adSet = $this->entity($campaign, '2001');

        $this->assertStringContainsString('ROAS goal', $this->capabilities()->lockedFields($adSet)['bid_strategy']);

        config(['campaign-manager.edit_categories' => ['name', 'budget', 'bid']]);
        $this->meta['adsets'][0]['bid_strategy'] = 'LOWEST_COST_WITHOUT_CAP';
        app(CampaignSynchronizer::class)->sync($campaign);
        $adSet->refresh();

        $this->assertStringContainsString('Bid strategy changes are not switched on', $this->capabilities()->lockedFields($adSet)['bid_strategy']);
        $this->assertNotContains('bid_amount', $this->capabilities()->editableFields($adSet));
    }

    public function test_the_form_only_shows_the_bid_when_the_chosen_strategy_reads_it(): void
    {
        $campaign = $this->campaign();
        $adSet = $this->entity($campaign, '2001');

        $this->actingAs($this->user);

        Livewire::test(EditEntity::class, ['campaign' => $campaign, 'entity' => $adSet])
            ->assertViewHas('fields', ['name', 'daily_budget', 'bid_strategy', 'pacing_type'])
            ->assertSee('Highest volume (no cap)')
            ->set('values.bid_strategy', 'COST_CAP')
            ->assertViewHas('fields', ['name', 'daily_budget', 'bid_strategy', 'bid_amount', 'pacing_type'])
            ->call('review')
            ->assertHasErrors('values.bid_strategy')
            ->set('values.bid_amount', '4.25')
            ->call('review')
            ->assertHasNoErrors()
            ->assertSee('Cost per result goal (cost cap)');
    }

    // ---------------------------------------------------------------- Google

    /** @param  array<string, mixed>  $profile */
    private function google(array &$profile): Mockery\MockInterface
    {
        $google = Mockery::mock(GoogleAdsService::class)->makePartial();
        $google->shouldReceive('readManagerCriteria')->andReturn([]);
        $google->shouldReceive('readCampaignProfile')->andReturnUsing(function () use (&$profile): array {
            return $profile;
        });
        $google->shouldReceive('readCampaignStructure')->andReturn(['ad_groups' => [], 'ads' => [], 'asset_groups' => []]);
        $this->app->instance(GoogleAdsService::class, $google);

        return $google;
    }

    private function googleCampaign(): Campaign
    {
        return $this->campaign(['platform' => 'google', 'ad_account_id' => '3460855874', 'external_campaign_id' => '987']);
    }

    /** @return array<string, mixed> */
    private function searchProfile(array $overrides = []): array
    {
        return ['id' => '987', 'name' => 'Search', 'status' => 'ENABLED', 'advertising_channel_type' => 'SEARCH',
            'bidding_strategy_type' => 'MAXIMIZE_CONVERSIONS', 'target_cpa' => null, 'target_roas' => null, ...$overrides];
    }

    public function test_a_google_campaign_gets_a_target_cpa_and_then_moves_to_a_roas_target(): void
    {
        $profile = $this->searchProfile();
        $google = $this->google($profile);
        $sent = [];
        $google->shouldReceive('updateLiveCampaign')->twice()
            ->andReturnUsing(function ($connection, string $id, array $fields) use (&$profile, &$sent): void {
                $sent[] = $fields;
                $profile = match (true) {
                    isset($fields['maximizeConversions']) => [...$profile, 'target_cpa' => ((int) $fields['maximizeConversions']['targetCpaMicros']) / 1_000_000],
                    default => [...$profile, 'bidding_strategy_type' => 'TARGET_ROAS', 'target_cpa' => null, 'target_roas' => $fields['maximizeConversionValue']['targetRoas']],
                };
            });

        $campaign = $this->googleCampaign();
        $entity = $this->entity($campaign, '987');

        $this->assertSame(['name', 'bid_strategy', 'target_cpa', 'target_roas'], $this->capabilities()->editableFields($entity));
        $this->assertSame(['MAXIMIZE_CONVERSIONS', 'MAXIMIZE_CONVERSION_VALUE', 'TARGET_SPEND', 'MANUAL_CPC'], array_keys(EditCapabilities::strategyOptions($entity)));

        $edit = $this->editor()->propose($campaign, $entity, $this->user, ['bid_strategy' => 'MAXIMIZE_CONVERSIONS', 'target_cpa' => '12.50', 'target_roas' => '']);
        $this->assertEquals(['target_cpa' => ['before' => null, 'after' => 12.5]], $edit->changes);
        $this->assertStringContainsString('A target is added', implode(' ', $this->capabilities()->confirmations($entity, $edit->changes)));
        $this->assertSame(CampaignEntityEdit::Applied, $this->editor()->apply($edit, $this->user, acknowledged: true)->state);

        $entity->refresh();
        $edit = $this->editor()->propose($campaign, $entity, $this->user, ['bid_strategy' => 'MAXIMIZE_CONVERSION_VALUE', 'target_cpa' => '12.50', 'target_roas' => '4']);
        $this->assertEquals([
            'bid_strategy' => ['before' => 'MAXIMIZE_CONVERSIONS', 'after' => 'MAXIMIZE_CONVERSION_VALUE'],
            'target_roas' => ['before' => null, 'after' => 4.0],
        ], $edit->changes);
        $edit = $this->editor()->apply($edit, $this->user, acknowledged: true);

        $this->assertSame(CampaignEntityEdit::Applied, $edit->state, (string) $edit->error);
        $this->assertEquals([
            ['maximizeConversions' => ['targetCpaMicros' => '12500000']],
            ['maximizeConversionValue' => ['targetRoas' => 4.0]],
        ], $sent);
        $this->assertSame('MAXIMIZE_CONVERSION_VALUE', EditCapabilities::current($entity->refresh(), 'bid_strategy'));
    }

    public function test_manual_cpc_is_sent_with_its_warning(): void
    {
        $profile = $this->searchProfile(['bidding_strategy_type' => 'TARGET_SPEND']);
        $google = $this->google($profile);
        $google->shouldReceive('updateLiveCampaign')->once()
            ->withArgs(fn ($connection, string $id, array $fields): bool => $id === '987' && $fields === ['manualCpc' => ['enhancedCpcEnabled' => false]])
            ->andReturnUsing(function () use (&$profile): void {
                $profile['bidding_strategy_type'] = 'MANUAL_CPC';
            });

        $campaign = $this->googleCampaign();
        $entity = $this->entity($campaign, '987');

        $edit = $this->editor()->propose($campaign, $entity, $this->user, ['bid_strategy' => 'MANUAL_CPC', 'target_cpa' => '5']);
        $this->assertSame(['bid_strategy'], array_keys($edit->changes));
        $this->assertStringContainsString('each ad group\'s max CPC', implode(' ', $this->capabilities()->confirmations($entity, $edit->changes)));

        $this->assertSame(CampaignEntityEdit::Applied, $this->editor()->apply($edit, $this->user, acknowledged: true)->state);
    }

    public function test_a_portfolio_strategy_and_other_channels_are_left_to_google(): void
    {
        $profile = $this->searchProfile(['bidding_portfolio' => 'customers/3460855874/biddingStrategies/77']);
        $this->google($profile)->shouldNotReceive('updateLiveCampaign');

        $campaign = $this->googleCampaign();
        $entity = $this->entity($campaign, '987');

        $this->assertSame(['name'], $this->capabilities()->editableFields($entity));
        $this->assertStringContainsString('portfolio strategy', $this->capabilities()->lockedFields($entity)['bid_strategy']);

        $profile = $this->searchProfile(['advertising_channel_type' => 'VIDEO']);
        app(CampaignSynchronizer::class)->sync($campaign);

        $this->assertStringContainsString('not video ones', $this->capabilities()->lockedFields($entity->refresh())['bid_strategy']);
    }

    public function test_performance_max_offers_only_conversion_strategies_and_display_targets_read_back(): void
    {
        $profile = $this->searchProfile(['advertising_channel_type' => 'PERFORMANCE_MAX']);
        $this->google($profile);

        $campaign = $this->googleCampaign();
        $entity = $this->entity($campaign, '987');

        $this->assertSame(['MAXIMIZE_CONVERSIONS', 'MAXIMIZE_CONVERSION_VALUE'], array_keys(EditCapabilities::strategyOptions($entity)));
        $this->assertRejected($campaign, $entity, ['bid_strategy' => 'TARGET_SPEND'], 'bid_strategy', 'invalid');

        // Display with a CPA target reports TARGET_CPA; it is the same strategy here.
        $profile = $this->searchProfile(['advertising_channel_type' => 'DISPLAY', 'bidding_strategy_type' => 'TARGET_CPA', 'target_cpa' => 8.0]);
        app(CampaignSynchronizer::class)->sync($campaign);
        $entity->refresh();

        $this->assertSame('MAXIMIZE_CONVERSIONS', EditCapabilities::current($entity, 'bid_strategy'));
        $this->assertSame(8.0, EditCapabilities::current($entity, 'target_cpa'));
        $this->assertSame(
            ['targetCpa' => ['targetCpaMicros' => '9000000']],
            app(GoogleAdsService::class)->biddingFor('target_cpa', 9.0, 'DISPLAY'),
        );
    }

    // -------------------------------------------------------------- LinkedIn

    /** @param  array<string, mixed>  $live */
    private function linkedin(array &$live): Mockery\MockInterface
    {
        $linkedin = Mockery::mock(LinkedIn::class);
        $linkedin->shouldReceive('campaignConversions')->andReturn([]);
        $linkedin->shouldReceive('on')->andReturnSelf();
        $linkedin->shouldReceive('campaign')->andReturnUsing(function () use (&$live): array {
            return $live;
        });
        $linkedin->shouldReceive('campaignGroup')->andReturn(['id' => 44, 'name' => 'Q4', 'status' => 'ACTIVE']);
        $linkedin->shouldReceive('creatives')->andReturn(['elements' => [], 'next_page_token' => null]);
        $this->app->instance(LinkedIn::class, $linkedin);

        return $linkedin;
    }

    public function test_a_linkedin_campaign_moves_between_the_strategies_its_objective_allows(): void
    {
        $live = ['id' => 555, 'name' => 'Visits', 'status' => 'ACTIVE', 'campaignGroup' => 'urn:li:sponsoredCampaignGroup:44',
            'objectiveType' => 'WEBSITE_VISIT', 'optimizationTargetType' => 'MAX_CLICK', 'costType' => 'CPC',
            'dailyBudget' => ['amount' => '50.00', 'currencyCode' => 'USD']];
        $this->linkedin($live)->shouldReceive('updateEntity')->once()
            ->with('urn:li:sponsoredAccount:999', 'campaign', '555', [
                'optimizationTargetType' => 'TARGET_COST_PER_CLICK',
                'unitCost' => ['amount' => '6.00', 'currencyCode' => 'USD'],
            ])
            ->andReturnUsing(function () use (&$live): void {
                $live = [...$live, 'optimizationTargetType' => 'TARGET_COST_PER_CLICK', 'unitCost' => ['amount' => '6.00', 'currencyCode' => 'USD']];
            });

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

        $this->assertSame([
            'NONE' => 'Manual bidding',
            'MAX_CLICK' => 'Maximum delivery (clicks)',
            'ENHANCED_CONVERSION' => 'Manual bidding, adjusted for conversions',
            'TARGET_COST_PER_CLICK' => 'Target cost (per click)',
            'CAP_COST_AND_MAXIMIZE_CLICKS' => 'Cost cap (per click)',
        ], EditCapabilities::strategyOptions($entity));
        $this->assertContains('unit_cost', $this->capabilities()->editableFields($entity));
        $this->assertRejected($campaign, $entity, ['bid_strategy' => 'TARGET_COST_PER_CLICK'], 'bid_strategy', 'Target cost (per click) needs a bid');
        $this->assertRejected($campaign, $entity, ['bid_strategy' => 'MAX_VIDEO_VIEW'], 'bid_strategy', 'invalid');

        $edit = $this->editor()->propose($campaign, $entity, $this->user, ['bid_strategy' => 'TARGET_COST_PER_CLICK', 'unit_cost' => '6']);
        $edit = $this->editor()->apply($edit, $this->user, acknowledged: true);

        $this->assertSame(CampaignEntityEdit::Applied, $edit->state, (string) $edit->error);
        $this->assertSame('TARGET_COST_PER_CLICK', EditCapabilities::current($entity->refresh(), 'bid_strategy'));
    }

    public function test_a_linkedin_objective_without_a_known_table_is_left_to_linkedin(): void
    {
        $live = ['id' => 555, 'name' => 'Other', 'status' => 'ACTIVE', 'campaignGroup' => 'urn:li:sponsoredCampaignGroup:44',
            'objectiveType' => 'SOMETHING_NEW', 'optimizationTargetType' => 'MAX_CLICK'];
        $this->linkedin($live)->shouldNotReceive('updateEntity');

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

        $this->assertStringContainsString('LinkedIn Campaign Manager', $this->capabilities()->lockedFields($this->entity($campaign, '555'))['bid_strategy']);
    }
}
