<?php

namespace App\Campaigns\Targeting;

use App\Models\Location;
use App\Models\PlatformLocation;
use RuntimeException;

class CountryCatalog
{
    public function __construct(private readonly CountryLookup $lookup) {}

    /** @return array<string, string> */
    public function names(): array
    {
        $stored = Location::query()->where('type', 'country')->pluck('name', 'iso_code')->all();

        return array_replace((array) config('countries'), $stored);
    }

    /** @return array<string, string> country code => verified external ID */
    public function verified(string $platform): array
    {
        return PlatformLocation::query()
            ->where('platform', $platform)
            ->where('status', 'verified')
            ->whereNotNull('verified_at')
            ->where('verified_at', '>=', now()->subDays(30))
            ->whereHas('location', fn ($query) => $query->where('type', 'country'))
            ->with('location:id,iso_code')
            ->get()
            ->mapWithKeys(fn (PlatformLocation $mapping): array => [$mapping->location->iso_code => $mapping->external_id])
            ->all();
    }

    /**
     * Resolve country IDs before the first remote mutation. Never substitute a
     * different region or omit a country when a provider returns no exact match.
     *
     * @param  list<string>  $codes
     * @return list<string>
     */
    public function resolve(string $platform, array $codes, ?string $adAccountId = null): array
    {
        if ($codes === []) {
            throw new RuntimeException('Choose at least one country before publishing.');
        }

        $names = $this->names();
        $verified = $this->verified($platform);
        $ids = [];

        foreach ($codes as $given) {
            $code = strtoupper(trim($given));
            if (! preg_match('/^[A-Z]{2}$/', $code) || ! isset($names[$code])) {
                throw new RuntimeException('Unrecognised country code: '.$given.'.');
            }

            $verifiedCount = PlatformLocation::query()
                ->where('platform', $platform)
                ->where('status', 'verified')
                ->whereNotNull('verified_at')
                ->where('verified_at', '>=', now()->subDays(30))
                ->whereHas('location', fn ($query) => $query->where('type', 'country')->where('iso_code', $code))
                ->count();

            if ($verifiedCount > 1) {
                $providerName = match ($platform) {
                    'linkedin' => 'LinkedIn',
                    'google' => 'Google',
                    'meta' => 'Meta',
                    default => ucfirst($platform),
                };

                throw new RuntimeException('Multiple verified '.$providerName.' country mappings exist for '.$code.'. Resolve the ambiguity before publishing.');
            }

            if (! isset($verified[$code])) {
                $found = $this->lookup->find($platform, $code, $names[$code], $adAccountId);
                if ($found === null) {
                    throw new RuntimeException(ucfirst($platform).' country mapping is not available for: '.$code.'. No campaign was created.');
                }

                if (PlatformLocation::query()->where('platform', $platform)->where('external_id', $found['id'])
                    ->whereHas('location', fn ($query) => $query->where('type', 'country')->where('iso_code', '!=', $code))
                    ->exists()) {
                    throw new RuntimeException('Selected countries share a provider location ID. Resolve the ambiguous mappings before publishing.');
                }

                $location = Location::query()->firstOrCreate(
                    ['iso_code' => $code],
                    ['type' => 'country', 'name' => $names[$code], 'country_code' => $code, 'source' => 'iso_3166_1', 'source_key' => $code],
                );

                PlatformLocation::query()->updateOrCreate(
                    ['platform' => $platform, 'location_id' => $location->id],
                    ['external_id' => $found['id'], 'provider_name' => $found['name'], 'status' => 'verified', 'verified_at' => now()],
                );
                $verified[$code] = $found['id'];
            }

            $ids[] = $verified[$code];
        }

        if (count(array_unique($ids)) !== count(array_unique(array_map(
            fn (string $code): string => strtoupper(trim($code)),
            $codes,
        )))) {
            throw new RuntimeException('Selected countries share a provider location ID. Resolve the ambiguous mappings before publishing.');
        }

        return array_values(array_unique($ids));
    }

    /**
     * Bind review to the exact verified rows as well as their provider IDs.
     * A deleted and recreated mapping needs a new review even if its ID matches.
     *
     * @param  list<string>  $codes
     * @return array<string, array{mapping_id: int, external_id: string}>
     */
    public function reviewedMappings(string $platform, array $codes, ?string $adAccountId = null): array
    {
        $this->resolve($platform, $codes, $adAccountId);

        $normalizedCodes = array_values(array_unique(array_map(
            fn (string $code): string => strtoupper(trim($code)),
            $codes,
        )));

        $mappings = PlatformLocation::query()
            ->where('platform', $platform)
            ->where('status', 'verified')
            ->whereNotNull('verified_at')
            ->where('verified_at', '>=', now()->subDays(30))
            ->whereHas('location', fn ($query) => $query->where('type', 'country')->whereIn('iso_code', $normalizedCodes))
            ->with('location:id,iso_code')
            ->get()
            ->keyBy(fn (PlatformLocation $mapping): string => $mapping->location->iso_code);

        $reviewed = [];

        foreach ($normalizedCodes as $code) {
            $mapping = $mappings->get($code);

            if ($mapping === null || blank($mapping->external_id)) {
                throw new RuntimeException('A verified country mapping changed during review. Review the country selection again.');
            }

            $reviewed[$code] = [
                'mapping_id' => $mapping->getKey(),
                'external_id' => $mapping->external_id,
            ];
        }

        return $reviewed;
    }
}
