<?php

namespace Tests\Feature;

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

class GoogleLocationMutationTest extends TestCase
{
    use RefreshDatabase;

    private function connection(): GoogleAdsConnection
    {
        config([
            'platforms.guardrails.allowed_ad_accounts' => ['1234567890'],
            'services.google_ads.oauth_client_id' => 'client-id',
            'services.google_ads.oauth_client_secret' => 'client-secret',
            'services.google_ads.developer_token' => 'developer-token',
        ]);

        return new GoogleAdsConnection(['customer_id' => '1234567890', 'refresh_token' => 'refresh-token']);
    }

    /** @return array<string, mixed> */
    private function country(): array
    {
        return [
            'criterion' => 'customers/1234567890/campaignCriteria/222~1',
            'geo_target' => 'geoTargetConstants/2840',
            'negative' => false,
            'status' => 'ENABLED',
            'target_type' => 'Country',
        ];
    }

    public function test_country_to_city_replacement_is_one_atomic_mutate_request(): void
    {
        Http::fake([
            'oauth2.googleapis.com/*' => Http::response(['access_token' => 'token']),
            '*campaignCriteria:mutate' => Http::response(['results' => [
                ['resourceName' => 'customers/1234567890/campaignCriteria/222~2'],
            ]]),
        ]);

        app(GoogleAdsService::class)->replaceCampaignLocationCriteria(
            $this->connection(), '222', [$this->country()], ['geoTargetConstants/1016864'],
        );

        $mutations = Http::recorded(fn ($request): bool => str_contains($request->url(), 'campaignCriteria:mutate'))->values();
        $this->assertCount(1, $mutations);
        $payload = $mutations[0][0]->data();
        $this->assertSame(false, $payload['partialFailure']);
        $this->assertSame([
            ['create' => [
                'campaign' => 'customers/1234567890/campaigns/222',
                'location' => ['geoTargetConstant' => 'geoTargetConstants/1016864'],
            ]],
            ['remove' => 'customers/1234567890/campaignCriteria/222~1'],
        ], $payload['operations']);
    }

    public function test_wrong_campaign_criterion_is_rejected_before_any_mutation(): void
    {
        Http::fake();
        $criterion = $this->country();
        $criterion['criterion'] = 'customers/1234567890/campaignCriteria/999~1';

        $this->expectException(RuntimeException::class);
        $this->expectExceptionMessage('mismatched location criterion');

        try {
            app(GoogleAdsService::class)->replaceCampaignLocationCriteria(
                $this->connection(), '222', [$criterion], ['geoTargetConstants/1016864'],
            );
        } finally {
            Http::assertNothingSent();
        }
    }

    public function test_negative_or_duplicate_geography_is_rejected(): void
    {
        Http::fake();
        $criterion = $this->country();
        $criterion['negative'] = true;

        try {
            app(GoogleAdsService::class)->replaceCampaignLocationCriteria(
                $this->connection(), '222', [$criterion], ['geoTargetConstants/1016864'],
            );
            $this->fail('Negative criteria must block replacement.');
        } catch (RuntimeException $exception) {
            $this->assertStringContainsString('unsupported', $exception->getMessage());
        }

        try {
            app(GoogleAdsService::class)->replaceCampaignLocationCriteria(
                $this->connection(), '222', [$this->country()], ['geoTargetConstants/1016864', 'geoTargetConstants/1016864'],
            );
            $this->fail('Duplicate target IDs must block replacement.');
        } catch (RuntimeException $exception) {
            $this->assertStringContainsString('unique', $exception->getMessage());
        }

        Http::assertNothingSent();

    }

    public function test_readback_accepts_a_complete_proximity_only_when_explicitly_requested(): void
    {
        Http::fake([
            'oauth2.googleapis.com/*' => Http::response(['access_token' => 'token']),
            '*googleAds:searchStream' => Http::sequence()
                ->push([['results' => []]])
                ->push([['results' => []]])
                ->push([['results' => [[
                    'campaignCriterion' => [
                        'proximity' => [
                            'geoPoint' => ['latitudeInMicroDegrees' => 40712776, 'longitudeInMicroDegrees' => -74005974],
                            'radius' => 10, 'radiusUnits' => 'MILES',
                        ],
                        'negative' => false, 'status' => 'ENABLED',
                    ],
                ]]]]),
        ]);

        $connection = $this->connection();
        $this->assertSame([], app(GoogleAdsService::class)->readCampaignLocationCriteria($connection, '222', true, true));
        $this->assertSame([[
            'latitude' => 40.712776, 'longitude' => -74.005974,
            'radius' => 10.0, 'radius_unit' => 'mi', 'negative' => false, 'status' => 'ENABLED',
        ]], app(GoogleAdsService::class)->readCampaignProximityCriteria($connection, '222'));

        $queries = Http::recorded(fn ($request): bool => str_contains($request->url(), 'googleAds:searchStream'))
            ->map(fn (array $recorded): string => (string) ($recorded[0]->data()['query'] ?? ''))->values()->all();
        $this->assertStringContainsString("campaign_criterion.type IN ('LOCATION_GROUP')", $queries[0]);
        $this->assertStringContainsString("campaign_criterion.type = 'PROXIMITY'", $queries[2]);
    }

    public function test_presence_readback_uses_the_campaign_setting(): void
    {
        Http::fake([
            'oauth2.googleapis.com/*' => Http::response(['access_token' => 'token']),
            '*googleAds:searchStream' => Http::response([['results' => [[
                'campaign' => ['geoTargetTypeSetting' => ['positiveGeoTargetType' => 'PRESENCE_OR_INTEREST']],
            ]]]]),
        ]);

        $mode = app(GoogleAdsService::class)->readCampaignGeoPresence($this->connection(), '222');

        $this->assertSame('PRESENCE_OR_INTEREST', $mode);
        Http::assertSent(fn ($request): bool => str_contains($request->url(), 'googleAds:searchStream')
            && str_contains((string) ($request->data()['query'] ?? ''), 'campaign.geo_target_type_setting.positive_geo_target_type'));
    }
}
