<?php

namespace Tests\Feature;

use App\Campaigns\Platforms\GoogleRules;
use App\Services\GoogleAdsService;
use Tests\TestCase;

/**
 * Where a Google bidding target lives, which is not one field everywhere.
 *
 * A buyer answered all twelve questions for a Search campaign with a $0.71
 * target CPA and publishing failed with "The operation is not allowed for the
 * given context [operations.create.target_cpa]". Google retired the standalone
 * TargetCpa and TargetRoas strategies for Search and Performance Max: the
 * target moved inside MaximizeConversions and MaximizeConversionValue. Display
 * did not move and still refuses the new shape.
 *
 * Every expectation below was checked against Google account 346-085-5874 with
 * validateOnly on each channel and both shapes, and the Search create and edit
 * were then run for real against that account, paused.
 */
class GoogleTakesItsBiddingTargetWhereItLivesTest extends TestCase
{
    private function google(): GoogleAdsService
    {
        return app(GoogleAdsService::class);
    }

    public function test_search_carries_its_target_cpa_inside_maximize_conversions(): void
    {
        $bidding = $this->google()->biddingFor('TARGET_CPA', 0.71, 'SEARCH');

        $this->assertSame(['maximizeConversions' => ['targetCpaMicros' => '710000']], $bidding);

        // The refused field, by name. This is the whole bug.
        $this->assertArrayNotHasKey('targetCpa', $bidding);
    }

    public function test_performance_max_carries_it_the_same_way_as_search(): void
    {
        $this->assertSame(
            ['maximizeConversions' => ['targetCpaMicros' => '710000']],
            $this->google()->biddingFor('TARGET_CPA', 0.71, 'PERFORMANCE_MAX'),
        );
    }

    public function test_display_keeps_the_field_google_still_wants_there(): void
    {
        $bidding = $this->google()->biddingFor('TARGET_CPA', 0.71, 'DISPLAY');

        // Display refuses maximize_conversions.target_cpa_micros, so sending
        // one shape everywhere trades this bug for the same bug on Display.
        $this->assertSame(['targetCpa' => ['targetCpaMicros' => '710000']], $bidding);
    }

    public function test_a_roas_target_moved_on_every_channel(): void
    {
        foreach (['SEARCH', 'DISPLAY', 'PERFORMANCE_MAX'] as $channel) {
            $this->assertSame(
                ['maximizeConversionValue' => ['targetRoas' => 4.0]],
                $this->google()->biddingFor('TARGET_ROAS', 4.0, $channel),
                $channel.' sent the retired target_roas field',
            );
        }
    }

    public function test_a_strategy_with_no_amount_does_not_ask_for_conversions_at_zero(): void
    {
        foreach (['SEARCH', 'DISPLAY', 'PERFORMANCE_MAX'] as $channel) {
            $bidding = $this->google()->biddingFor('TARGET_CPA', null, $channel);

            // It used to send targetCpaMicros "0", which is a real instruction
            // to Google: hold the cost per conversion at nothing.
            $this->assertSame(['maximizeConversions'], array_keys($bidding), $channel);
            $this->assertSame('{"maximizeConversions":{}}', json_encode($bidding), $channel);
        }
    }

    public function test_the_channel_follows_the_campaign_type(): void
    {
        $google = $this->google();

        $this->assertSame('SEARCH', $google->channelFor('search'));
        $this->assertSame('DISPLAY', $google->channelFor('display'));
        $this->assertSame('PERFORMANCE_MAX', $google->channelFor('performance_max'));

        // Video publishes as Performance Max; see createCampaign().
        $this->assertSame('PERFORMANCE_MAX', $google->channelFor('video'));

        // An unset type is a Search campaign everywhere else in the flow.
        $this->assertSame('SEARCH', $google->channelFor(null));
    }

    /**
     * The mask names leaves, because Google refuses one that names a block.
     *
     * FIELD_HAS_SUBFIELDS, which it also returned for the old "targetCpa" and
     * still returns for "networkSettings", so no edit to a live campaign's
     * bidding or networks ever reached Google.
     */
    public function test_the_update_mask_names_leaves_rather_than_blocks(): void
    {
        $mask = new \ReflectionMethod($this->google(), 'updateMask');
        $mask->setAccessible(true);

        $this->assertSame(
            'maximizeConversions.targetCpaMicros',
            $mask->invoke($this->google(), ['maximizeConversions' => ['targetCpaMicros' => '710000']]),
        );

        $this->assertSame(
            'networkSettings.targetGoogleSearch,networkSettings.targetSearchNetwork',
            $mask->invoke($this->google(), ['networkSettings' => [
                'targetGoogleSearch' => true,
                'targetSearchNetwork' => false,
            ]]),
        );

        // A flat field is still named flat, and several fields still comma join.
        $this->assertSame(
            'name,startDateTime',
            $mask->invoke($this->google(), ['name' => 'x', 'startDateTime' => '2026-01-01 00:00:00']),
        );
    }

    /**
     * Switching to a strategy that has no target at all.
     *
     * The block is empty, and the mask still has to name a field inside it:
     * Google picks the strategy from whichever one-of block the mask names, and
     * the absent value is what clears the target the old strategy carried.
     *
     * Masking bidding_strategy_type instead is accepted and does nothing - it
     * is output only - so this was checked by running each switch for real on a
     * paused campaign on account 346-085-5874 and reading the strategy back.
     */
    public function test_a_strategy_with_no_target_is_still_masked_at_a_leaf(): void
    {
        $mask = new \ReflectionMethod($this->google(), 'updateMask');
        $mask->setAccessible(true);

        foreach ([
            'MAXIMIZE_CONVERSIONS' => 'maximizeConversions.targetCpaMicros',
            'MAXIMIZE_CONVERSION_VALUE' => 'maximizeConversionValue.targetRoas',
            'MAXIMIZE_CLICKS' => 'targetSpend.cpcBidCeilingMicros',
        ] as $strategy => $expected) {
            $bidding = $this->google()->biddingFor($strategy, null, 'SEARCH');

            // The premise: these really do send an empty block.
            $this->assertSame('{}', json_encode(reset($bidding)), $strategy);

            $this->assertSame($expected, $mask->invoke($this->google(), $bidding), $strategy);

            // The block name alone is what Google refuses.
            $this->assertStringContainsString('.', $mask->invoke($this->google(), $bidding), $strategy);
        }
    }

    /** A target CPA dropped on the way to a no-target strategy is the point. */
    public function test_switching_away_from_a_target_clears_it(): void
    {
        $mask = new \ReflectionMethod($this->google(), 'updateMask');
        $mask->setAccessible(true);

        $bidding = $this->google()->biddingFor('MAXIMIZE_CONVERSIONS', null, 'SEARCH');

        // Masked but absent: Google clears any field the mask names and the
        // payload omits, which is exactly how the old target goes away.
        $this->assertSame('maximizeConversions.targetCpaMicros', $mask->invoke($this->google(), $bidding));
        $this->assertArrayNotHasKey('targetCpaMicros', (array) $bidding['maximizeConversions']);
    }

    public function test_performance_max_is_not_offered_bidding_it_cannot_take(): void
    {
        $rules = app(GoogleRules::class);

        foreach (['performance_max', 'video'] as $type) {
            $strategies = $rules->bidStrategies('SALES', $type);

            // Google refuses target_spend and manual_cpc on Performance Max.
            $this->assertNotContains('MAXIMIZE_CLICKS', $strategies, $type);
            $this->assertNotContains('MANUAL_CPC', $strategies, $type);
            $this->assertContains('MAXIMIZE_CONVERSIONS', $strategies, $type);
            $this->assertContains('TARGET_CPA', $strategies, $type);

            // And the buttons match the list, or the buyer picks one the next
            // step refuses.
            $this->assertSame(
                $strategies,
                array_column($rules->bidStrategyOptions('SALES', $type), 'value'),
                $type.' offered different buttons from its own allowed list',
            );
        }
    }

    public function test_search_and_display_still_offer_all_six(): void
    {
        $rules = app(GoogleRules::class);

        foreach (['search', 'display', null] as $type) {
            $strategies = $rules->bidStrategies('SALES', $type);

            $this->assertContains('MAXIMIZE_CLICKS', $strategies, (string) $type);
            $this->assertContains('MANUAL_CPC', $strategies, (string) $type);
            $this->assertCount(6, $strategies, (string) $type);
        }
    }
}
