<?php

namespace App\Campaigns\Targeting;

use App\Models\GoogleAdsConnection;
use App\Models\Location;
use App\Models\PlatformLocation;
use App\Services\GoogleAdsService;
use App\Services\LinkedIn\LinkedInRestApi;
use App\Services\Meta\GraphApi;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\DB;
use RuntimeException;

class LocationDiscovery
{
    public function __construct(
        private readonly GoogleAdsService $google,
        private readonly GraphApi $meta,
        private readonly LinkedInRestApi $linkedin,
    ) {}

    /**
     * @return list<array{platform: string, external_id: string, kind: string, name: string, label: string, country_code: string, parent_external_id: string|null}>
     */
    public function search(string $platform, string $kind, string $countryCode, string $term, ?string $accountId = null, int $page = 1): array
    {
        $cacheKey = 'location-search:'.hash('sha256', implode('|', [
            $platform, $kind, $countryCode, mb_strtolower(trim($term)), $accountId ?? '', (string) $page,
        ]));

        return Cache::remember($cacheKey, now()->addDay(), fn (): array => $this->providerSearch($platform, $kind, $countryCode, $term, $accountId, $page));
    }

    /**
     * Every region Meta returns for a country, with the key Meta expects.
     *
     * @return list<array{platform: string, external_id: string, kind: string, name: string, label: string, country_code: string, parent_external_id: string|null}>
     */
    public function regions(string $platform, string $countryCode, ?string $accountId = null): array
    {
        if ($platform !== 'meta') {
            return [];
        }

        $cacheKey = 'location-regions:'.hash('sha256', implode('|', [$platform, $countryCode, $accountId ?? '']));
        $cached = Cache::get($cacheKey);

        if (is_array($cached) && $cached !== []) {
            return $cached;
        }

        $results = [];

        foreach ($this->meta->regionsInCountry($countryCode, $accountId) as $candidate) {
            if (($candidate['type'] ?? null) !== 'region'
                || ($candidate['country_code'] ?? null) !== $countryCode
                || blank($candidate['key'] ?? null)
                || blank($candidate['name'] ?? null)) {
                continue;
            }

            $results[(string) $candidate['key']] = [
                'platform' => 'meta',
                'external_id' => (string) $candidate['key'],
                'kind' => 'region',
                'name' => (string) $candidate['name'],
                'label' => implode(', ', array_filter([
                    (string) $candidate['name'],
                    $countryCode,
                ])),
                'country_code' => $countryCode,
                'parent_external_id' => null,
            ];
        }

        $results = array_values($results);
        usort($results, fn (array $left, array $right): int => strcasecmp($left['name'], $right['name']));

        if ($results !== []) {
            Cache::put($cacheKey, $results, now()->addDay());
        }

        return $results;
    }

    /**
     * Verify a chosen provider ID again before saving it. A similarly named
     * location or an old search result cannot silently become the selection.
     */
    public function select(string $platform, string $kind, string $countryCode, string $term, string $externalId, ?string $accountId = null, int $page = 1): PlatformLocation
    {
        $isChosen = fn (array $candidate): bool => $candidate['external_id'] === $externalId;

        // The cached search first: a 50-place list would otherwise cost a second Graph call per place.
        $matches = array_values(array_filter($this->search($platform, $kind, $countryCode, $term, $accountId, $page), $isChosen));

        if ($matches === []) {
            $matches = array_values(array_filter(
                $this->providerSearch($platform, $kind, $countryCode, $term, $accountId, $page),
                $isChosen,
            ));
        }

        if (count($matches) !== 1) {
            throw new RuntimeException('The chosen location is no longer available. Search again before selecting it.');
        }

        $chosen = $matches[0];

        if ($platform === 'meta' && $kind === 'dma') {
            $this->meta->marketAudienceEstimate($accountId
                ?? throw new RuntimeException('Verify the Meta ad account before selecting a market.'), $externalId);
        }

        if ($platform === 'linkedin' && $kind === 'dma') {
            $this->linkedin->dmaAudienceCount($externalId, $accountId
                ?? throw new RuntimeException('Verify the LinkedIn ad account before selecting a DMA market.'));
        }

        return DB::transaction(function () use ($chosen): PlatformLocation {
            $country = Location::query()->where('type', 'country')->where('iso_code', $chosen['country_code'])->first()
                ?? throw new RuntimeException('Seed the country catalog before saving a location.');

            $existing = PlatformLocation::query()
                ->where('platform', $chosen['platform'])
                ->where('external_id', $chosen['external_id'])
                ->first();

            if ($existing !== null) {
                if ($existing->location->type !== $chosen['kind']
                    || $existing->location->country_code !== $chosen['country_code']
                    || $existing->location->name !== $chosen['name']
                    || $existing->provider_name !== $chosen['label']
                    || ($existing->parent_external_id !== null && $existing->parent_external_id !== $chosen['parent_external_id'])) {
                    throw new RuntimeException('This provider location changed its name or parent. Review its mapping before selecting it again.');
                }

                $existing->update([
                    'parent_external_id' => $chosen['parent_external_id'],
                    'status' => 'verified',
                    'verified_at' => now(),
                ]);

                return $existing;
            }

            $parent = PlatformLocation::query()
                ->where('platform', $chosen['platform'])
                ->where('external_id', $chosen['parent_external_id'])
                ->first()?->location;

            $location = Location::query()->firstOrCreate(
                ['type' => $chosen['kind'], 'source' => $chosen['platform'], 'source_key' => $chosen['external_id']],
                [
                    'name' => $chosen['name'],
                    'country_code' => $chosen['country_code'],
                    'parent_id' => $parent?->getKey() ?? $country->getKey(),
                ],
            );

            return PlatformLocation::query()->create([
                'location_id' => $location->getKey(),
                'platform' => $chosen['platform'],
                'external_id' => $chosen['external_id'],
                'parent_external_id' => $chosen['parent_external_id'],
                'provider_name' => $chosen['label'],
                'status' => 'verified',
                'verified_at' => now(),
            ]);
        });
    }

    /**
     * @return list<array{platform: string, external_id: string, kind: string, name: string, label: string, country_code: string, parent_external_id: string|null}>
     */
    private function providerSearch(string $platform, string $kind, string $countryCode, string $term, ?string $accountId, int $page): array
    {
        if (! in_array($kind, ['city', 'region', 'dma', 'postal'], true) || ! preg_match('/^[A-Z]{2}$/D', $countryCode)) {
            throw new RuntimeException('Choose a city, region, postal code, or US DMA market and a valid country.');
        }

        if ($kind === 'dma' && ($countryCode !== 'US' || ! in_array($platform, ['google', 'meta', 'linkedin'], true))) {
            throw new RuntimeException('DMA market discovery is available for US campaigns on Google, Meta, and LinkedIn only.');
        }

        if ($platform === 'google') {
            if ($page !== 1) {
                throw new RuntimeException('Google city and region search does not support additional pages yet. Refine the search term.');
            }

            $connection = GoogleAdsConnection::shared()
                ?? throw new RuntimeException(GoogleAdsConnection::missingReason());

            // Searched as the account that was asked for, rather than refused
            // for not being the configured one - the second copy of the guard
            // that stopped Mohsin narrowing his targeting; see choose_location
            // for the whole of it. $accountId is passed straight through to
            // geoTargetCandidates(), which addresses the read to that customer,
            // so nothing has to be swapped on the connection here.
            if (blank($accountId)) {
                throw new RuntimeException('Verify the Google Ads account before searching for locations.');
            }

            return array_map(fn (array $candidate): array => [
                'platform' => 'google',
                'external_id' => $candidate['id'],
                'kind' => $candidate['kind'],
                'name' => $candidate['name'],
                'label' => $candidate['label'],
                'country_code' => $candidate['country_code'],
                'parent_external_id' => $candidate['parent_id'],
            ], $this->google->geoTargetCandidates($connection, $kind, $countryCode, $term, $accountId));
        }

        if ($platform === 'meta') {
            $results = [];

            foreach ($this->meta->locationCandidates($kind, $countryCode, $term, $accountId, $page) as $candidate) {
                if (($candidate['type'] ?? null) !== match ($kind) {
                    'dma' => 'geo_market', 'postal' => 'zip', default => $kind,
                }
                    || ($candidate['country_code'] ?? null) !== $countryCode
                    || blank($candidate['key'] ?? null)
                    || blank($candidate['name'] ?? null)
                    || ($kind === 'dma' && ! preg_match('/^COMSCORE_MARKET:[0-9]+$/D', (string) $candidate['key']))) {
                    continue;
                }

                $region = (string) ($candidate['region'] ?? '');
                $results[] = [
                    'platform' => 'meta',
                    'external_id' => (string) $candidate['key'],
                    'kind' => $kind,
                    'name' => (string) ($candidate['name'] ?? ''),
                    'label' => implode(', ', array_filter([
                        (string) ($candidate['name'] ?? ''),
                        $kind === 'postal' ? (string) ($candidate['primary_city'] ?? '') : '',
                        $region,
                        $countryCode,
                    ])),
                    'country_code' => $countryCode,
                    'parent_external_id' => filled($candidate['region_id'] ?? null) ? (string) $candidate['region_id'] : null,
                ];
            }

            return $results;
        }

        if ($platform === 'linkedin' && $kind === 'dma') {
            if ($page !== 1 || $accountId === null || ! preg_match('/^[\pL\pN .,-]{2,80}$/uD', trim($term))) {
                throw new RuntimeException('Verify the LinkedIn account and search a US DMA market by name.');
            }

            $results = [];

            foreach ($this->linkedin->countryCandidates($term, $accountId) as $candidate) {
                $label = (string) ($candidate['name'] ?? '');
                $urn = (string) ($candidate['urn'] ?? '');

                if (($candidate['facetUrn'] ?? null) !== 'urn:li:adTargetingFacet:locations'
                    || ! preg_match('/^urn:li:geo:[0-9]+$/D', $urn)
                    || ! preg_match('/^DMA® [0-9]+ - (.+), United States$/uD', $label, $matches)) {
                    continue;
                }

                $results[] = [
                    'platform' => 'linkedin', 'external_id' => $urn, 'kind' => 'dma',
                    'name' => $matches[1], 'label' => $label, 'country_code' => 'US',
                    'parent_external_id' => null,
                ];
            }

            return $results;
        }

        throw new RuntimeException('City and region search is not verified for '.$platform.'.');
    }
}
