<?php

namespace Tests\Feature;

use App\Models\GoogleAdsConnection;
use App\Services\GoogleAdsService;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Http\Client\Request;
use Illuminate\Support\Facades\Http;
use Tests\TestCase;

/**
 * "Not all conversion goals were selected in the launched campaign. Selected
 * 4, out of that only 2 were seen."
 *
 * Reported on campaign 24377550714, published to account 2099157735. He chose
 * Subscribe, Begin checkout and Continue-General Info; the campaign came back
 * with BEGIN_CHECKOUT and SUBMIT_LEAD_FORM biddable and SUBSCRIBE_PAID not -
 * which was also the one stored as the campaign's primary.
 *
 * narrowConversionGoals() only ever switched categories off. Its docblock said
 * Google creates a new campaign's goals "every one of them biddable", so
 * turning the unwanted ones off was enough. That is not where they come from:
 * a campaign inherits the account's customer_conversion_goal settings, and on
 * his account SUBSCRIBE_PAID is not biddable at the account level. So the
 * category he picked started off and nothing ever turned it on, and the
 * campaign silently did not count the conversion it was asked to optimise for.
 *
 * Both directions now, and only where the goal is not already right.
 */
class EveryChosenConversionGoalIsCountedTest extends TestCase
{
    use RefreshDatabase;

    /** @var list<array<string,mixed>> */
    private array $goalOperations = [];

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

        config([
            'platforms.guardrails.paused' => false,
            'platforms.guardrails.allowed_ad_accounts' => ['google:1234567890'],
            'services.google_ads.refresh_token' => 'refresh-token',
            'services.google_ads.customer_id' => '123-456-7890',
        ]);
    }

    /**
     * His account's shape: five categories, and the one he cares about is off.
     *
     * biddable is absent rather than false on the goals Google considers off,
     * which is how it reports them.
     */
    private function fakeGoogle(): void
    {
        $this->goalOperations = [];

        Http::fake(function (Request $request) {
            if (str_contains($request->url(), 'oauth2.googleapis.com')) {
                return Http::response(['access_token' => 'token', 'expires_in' => 3600]);
            }

            if (str_contains($request->url(), 'googleAds:searchStream')) {
                $query = (string) ($request->data()['query'] ?? '');

                if (str_contains($query, 'campaign_conversion_goal')) {
                    return Http::response([['results' => [
                        ['campaignConversionGoal' => ['category' => 'PURCHASE', 'origin' => 'WEBSITE', 'biddable' => true]],
                        ['campaignConversionGoal' => ['category' => 'DOWNLOAD', 'origin' => 'APP', 'biddable' => true]],
                        ['campaignConversionGoal' => ['category' => 'BEGIN_CHECKOUT', 'origin' => 'WEBSITE', 'biddable' => true]],
                        // Off on the account, so off on the campaign.
                        ['campaignConversionGoal' => ['category' => 'SUBSCRIBE_PAID', 'origin' => 'WEBSITE']],
                        ['campaignConversionGoal' => ['category' => 'SUBMIT_LEAD_FORM', 'origin' => 'WEBSITE', 'biddable' => true]],
                    ]]]);
                }

                if (str_contains($query, 'conversion_action')) {
                    return Http::response([['results' => [
                        ['conversionAction' => [
                            'resourceName' => 'customers/1234567890/conversionActions/1',
                            'name' => 'Subscribe', 'category' => 'SUBSCRIBE_PAID', 'type' => 'WEBPAGE',
                        ]],
                        ['conversionAction' => [
                            'resourceName' => 'customers/1234567890/conversionActions/2',
                            'name' => 'Begin checkout', 'category' => 'BEGIN_CHECKOUT', 'type' => 'WEBPAGE',
                        ]],
                        ['conversionAction' => [
                            'resourceName' => 'customers/1234567890/conversionActions/3',
                            'name' => 'Continue-General Info', 'category' => 'SUBMIT_LEAD_FORM', 'type' => 'WEBPAGE',
                        ]],
                    ]]]);
                }

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

            if (str_contains($request->url(), 'campaignConversionGoals:mutate')) {
                $this->goalOperations = (array) data_get($request->data(), 'operations', []);

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

            if (str_contains($request->url(), 'campaignBudgets:mutate')) {
                return Http::response(['results' => [['resourceName' => 'customers/1234567890/campaignBudgets/1']]]);
            }

            if (str_contains($request->url(), 'campaigns:mutate')) {
                return Http::response(['results' => [['resourceName' => 'customers/1234567890/campaigns/55']]]);
            }

            if (str_contains($request->url(), 'adGroups:mutate')) {
                return Http::response(['results' => [['resourceName' => 'customers/1234567890/adGroups/66']]]);
            }

            if (str_contains($request->url(), 'adGroupAds:mutate')) {
                return Http::response(['results' => [['resourceName' => 'customers/1234567890/adGroupAds/66~77']]]);
            }

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

    /** Publish choosing the three he chose. */
    private function publish(): void
    {
        $this->fakeGoogle();

        $created = [];

        app(GoogleAdsService::class)->createPausedCampaign(
            GoogleAdsConnection::shared(),
            [
                'name' => 'Conversion goals',
                'campaign_type' => 'search',
                'daily_budget' => 10,
                'final_url' => 'https://stockprices.com/landing',
                'ad_group_name' => 'Ad group 1',
                'headlines' => ['Headline one', 'Headline two', 'Headline three'],
                'descriptions' => ['Description one here', 'Description two here'],
                'keyword_criteria' => [['text' => 'stock analysis', 'match_type' => 'PHRASE', 'negative' => false]],
                'geo_targets' => ['geoTargetConstants/2840'],
                'conversion_action' => 'customers/1234567890/conversionActions/1',
                'conversion_actions' => [
                    'customers/1234567890/conversionActions/1',
                    'customers/1234567890/conversionActions/2',
                    'customers/1234567890/conversionActions/3',
                ],
            ],
            $created,
        );
    }

    /** @return array<string,bool> category to the biddable value sent for it */
    private function sent(): array
    {
        $sent = [];

        foreach ($this->goalOperations as $operation) {
            $resource = (string) data_get($operation, 'update.resourceName');
            $parts = explode('~', $resource);

            if (count($parts) === 3) {
                $sent[$parts[1]] = (bool) data_get($operation, 'update.biddable');
            }
        }

        return $sent;
    }

    /** The defect: the category he picked was never switched on. */
    public function test_a_chosen_category_the_account_has_off_is_switched_on(): void
    {
        $this->publish();

        $this->assertSame(
            true,
            $this->sent()['SUBSCRIBE_PAID'] ?? null,
            'the chosen conversion goal was left off, so the campaign does not count it',
        );
    }

    /** Everything he did not pick is still switched off. */
    public function test_the_categories_nobody_chose_are_switched_off(): void
    {
        $this->publish();

        $sent = $this->sent();

        $this->assertFalse($sent['PURCHASE'] ?? null);
        $this->assertFalse($sent['DOWNLOAD'] ?? null);
    }

    /** A goal already in the right state is left alone rather than rewritten. */
    public function test_goals_that_are_already_right_are_not_touched(): void
    {
        $this->publish();

        $sent = $this->sent();

        // Chosen and already biddable on the account.
        $this->assertArrayNotHasKey('BEGIN_CHECKOUT', $sent);
        $this->assertArrayNotHasKey('SUBMIT_LEAD_FORM', $sent);
    }

    /** Every chosen category ends up counted, however the account is set. */
    public function test_all_three_chosen_categories_are_biddable_afterwards(): void
    {
        $this->publish();

        $sent = $this->sent();

        foreach (['SUBSCRIBE_PAID' => true, 'BEGIN_CHECKOUT' => null, 'SUBMIT_LEAD_FORM' => null] as $category => $expected) {
            // Either it was switched on, or it was already on and left alone.
            $this->assertNotFalse(
                $sent[$category] ?? null,
                $category.' was switched off, and the buyer chose it',
            );
        }
    }

    /** The origin is part of the goal, so it has to survive the round trip. */
    public function test_the_operation_names_the_goal_by_category_and_origin(): void
    {
        $this->publish();

        $resources = array_map(
            static fn (array $operation): string => (string) data_get($operation, 'update.resourceName'),
            $this->goalOperations,
        );

        $this->assertContains('customers/1234567890/campaignConversionGoals/55~SUBSCRIBE_PAID~WEBSITE', $resources);
        $this->assertContains('customers/1234567890/campaignConversionGoals/55~DOWNLOAD~APP', $resources);
    }

    /** Nothing is sent at all when no conversion action was chosen. */
    public function test_no_choice_means_no_change(): void
    {
        $this->fakeGoogle();

        $created = [];

        app(GoogleAdsService::class)->createPausedCampaign(
            GoogleAdsConnection::shared(),
            [
                'name' => 'No conversion choice',
                'campaign_type' => 'search',
                'daily_budget' => 10,
                'final_url' => 'https://stockprices.com/landing',
                'ad_group_name' => 'Ad group 1',
                'headlines' => ['Headline one', 'Headline two', 'Headline three'],
                'descriptions' => ['Description one here', 'Description two here'],
                'keyword_criteria' => [['text' => 'stock analysis', 'match_type' => 'PHRASE', 'negative' => false]],
                'geo_targets' => ['geoTargetConstants/2840'],
            ],
            $created,
        );

        $this->assertSame([], $this->goalOperations);
    }
}
