<?php

namespace Tests\Feature;

use App\Agent\Answers;
use App\Agent\Choices;
use App\Agent\Tools\Campaign\ChooseLocation;
use App\Agent\Workspace;
use App\Campaigns\Targeting\LocationDiscovery;
use App\Campaigns\Targeting\TargetingSelections;
use App\Models\Campaign;
use App\Models\Location;
use App\Models\PlatformLocation;
use App\Models\User;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Http\Client\Request as ClientRequest;
use Illuminate\Support\Facades\Http;
use Laravel\Ai\Tools\Request;
use Tests\TestCase;

/**
 * "Not allowing to select [a state or region] or city."
 *
 * Read from Mohsin's two conversations on 21 Oct. He chose "state or region",
 * got the search field, ticked the saved places and submitted - three times,
 * twice for regions and once for cities - and each time the answer came back
 * "Not accepted: location search. Those options had already moved on". He gave
 * up and kept whole-country targeting.
 *
 * Nothing had moved on. His campaign was on account 2099157735, and both
 * choose_location and LocationDiscovery required the campaign's account to be
 * the one Google is configured with - 3460855874. So every Google campaign on
 * any other account could not narrow its targeting at all: not a city, not a
 * region, not a market, whether the place was typed or ticked.
 *
 * This is the same assumption that was offering knowledgedomain's conversion
 * actions to a stockprices campaign, and it was true while the allow list held
 * one account. It stopped being true when the list was opened and the flow
 * began asking which of the manager's children to buy on.
 *
 * Geo targets are not account-scoped on Google - a geoTargetConstant means the
 * same thing on every customer - so the account here only decides who the call
 * is billed and attributed to. onCustomer() already exists for that, and
 * choose_pixel was converted to it; these two were missed.
 */
class LocationsReadTheCampaignsAccountNotTheConfiguredOneTest extends TestCase
{
    use RefreshDatabase;

    /** The campaign's account, which is not the configured one. */
    private const CAMPAIGN_ACCOUNT = '2099157735';

    private Campaign $campaign;

    /** @var list<string> */
    private array $catalogIds = [];

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

        config([
            'platforms.guardrails.paused' => false,
            // Both permitted, which is the situation that exposed this.
            'platforms.guardrails.allowed_ad_accounts' => ['google:3460855874', 'google:'.self::CAMPAIGN_ACCOUNT],
            'services.google_ads.refresh_token' => 'refresh-token',
            'services.google_ads.customer_id' => '346-085-5874',
            'services.google_ads.login_customer_id' => '803-900-0543',
        ]);

        // Google's own geo_target_constant rows, answered by name, because
        // select() re-verifies each place against the provider by searching
        // for its name and expecting exactly one match on that id.
        $places = [
            'Illinois' => ['geoTargetConstants/21147', 'Illinois,United States', 'State'],
            'Texas' => ['geoTargetConstants/21176', 'Texas,United States', 'State'],
            'Chicago' => ['geoTargetConstants/1016367', 'Chicago,Illinois,United States', 'City'],
        ];

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

            $query = (string) ($request->data()['query'] ?? '');
            $results = [];

            foreach ($places as $name => [$resource, $canonical, $type]) {
                if (! str_contains($query, "'%".$name."%'")) {
                    continue;
                }

                $results[] = ['geoTargetConstant' => [
                    'resourceName' => $resource,
                    'name' => $name,
                    'canonicalName' => $canonical,
                    'countryCode' => 'US',
                    'targetType' => $type,
                    'status' => 'ENABLED',
                ]];
            }

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

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

        $this->campaign = Campaign::create([
            'user_id' => $user->getKey(),
            'name' => 'Trade Smarter',
            'platform' => 'google',
            'campaign_type' => 'search',
            'status' => 'draft',
            'ad_account_id' => self::CAMPAIGN_ACCOUNT,
            'objective' => 'SALES',
            'landing_url' => 'https://stockprices.com/landing',
        ]);

        app(Workspace::class)->bindTo('mohsin-locations');
        app(Workspace::class)->focusOn($this->campaign);
        app(TargetingSelections::class)->saveCampaignCountries($this->campaign, ['US']);

        // Saved places, as an earlier search leaves behind. iso_code is null
        // because the factory defaults to a country and that column is unique.
        foreach ([['Illinois', 'geoTargetConstants/21147'], ['Texas', 'geoTargetConstants/21176']] as [$name, $external]) {
            $location = Location::factory()->create([
                'type' => 'region', 'name' => $name, 'country_code' => 'US', 'iso_code' => null,
            ]);

            $this->catalogIds[] = (string) PlatformLocation::factory()->create([
                'location_id' => $location->getKey(),
                'platform' => 'google',
                'external_id' => $external,
                'provider_name' => $name.',United States',
                'status' => 'verified',
            ])->getKey();
        }
    }

    /** Offer the scope question and click the scope, which opens the search. */
    private function openTheSearch(string $scope): void
    {
        app(ChooseLocation::class)->handle(new Request([]));
        app(Workspace::class)->rememberChoices(app(Choices::class)->drain());

        $this->assertTrue(
            app(Answers::class)->apply('location_scope', $scope),
            'the scope click was refused',
        );

        app(Workspace::class)->rememberChoices(app(Choices::class)->drain());
    }

    /** His exact move: tick the saved places, submit. */
    public function test_ticking_the_saved_regions_is_accepted(): void
    {
        $this->openTheSearch('region');

        $this->assertTrue(app(Answers::class)->apply('location_search', [
            'kind' => 'region',
            'country_code' => 'US',
            'catalog_places' => $this->catalogIds,
        ]), 'ticking the saved regions was refused');

        $this->assertSame(
            ['geoTargetConstants/21147', 'geoTargetConstants/21176'],
            array_column(app(TargetingSelections::class)->selectedCampaignLocations($this->campaign->fresh(), 'US'), 'external_id'),
        );
    }

    /** And typing one, which is the same tool and the same guard. */
    public function test_typing_a_region_name_is_accepted(): void
    {
        $this->openTheSearch('region');

        $this->assertTrue(app(Answers::class)->apply('location_search', [
            'kind' => 'region',
            'country_code' => 'US',
            'query' => 'Illinois',
        ]), 'searching for a region was refused');

        $offered = collect(app(Choices::class)->drain())->firstWhere('field', 'google_location');

        $this->assertNotNull($offered, 'no matching places came back');
    }

    /** Cities too, which is the other half of what he reported. */
    public function test_a_city_search_is_accepted(): void
    {
        $this->openTheSearch('city');

        $this->assertTrue(app(Answers::class)->apply('location_search', [
            'kind' => 'city',
            'country_code' => 'US',
            'query' => 'Chicago',
        ]), 'searching for a city was refused');
    }

    /**
     * The call goes out as the campaign's customer.
     *
     * The point is not only that it is allowed but that it is attributed to the
     * account the campaign runs on, the way every other read in the flow now is.
     */
    public function test_the_search_is_addressed_to_the_campaigns_customer(): void
    {
        $this->openTheSearch('region');

        app(Answers::class)->apply('location_search', [
            'kind' => 'region', 'country_code' => 'US', 'query' => 'Illinois',
        ]);

        $customers = [];

        foreach (Http::recorded() as [$request]) {
            if (preg_match('#/customers/(\d+)[:/]#', (string) $request->url(), $matches) === 1) {
                $customers[] = $matches[1];
            }
        }

        $this->assertSame([self::CAMPAIGN_ACCOUNT], array_values(array_unique($customers)));
    }

    /** An account nobody permitted is still refused. */
    public function test_an_account_that_is_not_allowed_is_still_refused(): void
    {
        config(['platforms.guardrails.allowed_ad_accounts' => ['google:3460855874']]);

        $this->openTheSearch('region');

        $this->assertFalse(app(Answers::class)->apply('location_search', [
            'kind' => 'region',
            'country_code' => 'US',
            'query' => 'Illinois',
        ]), 'a campaign on an unpermitted account was allowed to read locations');
    }

    /** A campaign with no account at all cannot search either. */
    public function test_a_campaign_without_an_account_is_refused(): void
    {
        $this->openTheSearch('region');
        $this->campaign->update(['ad_account_id' => null]);

        $this->assertFalse(app(Answers::class)->apply('location_search', [
            'kind' => 'region',
            'country_code' => 'US',
            'query' => 'Illinois',
        ]));
    }

    /** The configured account keeps working, which is the common case. */
    public function test_the_configured_account_still_works(): void
    {
        $this->campaign->update(['ad_account_id' => '3460855874']);

        $this->openTheSearch('region');

        $this->assertTrue(app(Answers::class)->apply('location_search', [
            'kind' => 'region',
            'country_code' => 'US',
            'query' => 'Illinois',
        ]));
    }

    /** Discovery is where the second copy of the guard was. */
    public function test_discovery_searches_on_the_given_account(): void
    {
        $found = app(LocationDiscovery::class)->search('google', 'region', 'US', 'Illinois', self::CAMPAIGN_ACCOUNT, 1);

        $this->assertNotSame([], $found);
        $this->assertSame('geoTargetConstants/21147', $found[0]['external_id']);
    }
}
