<?php

namespace App\Campaigns\Targeting;

use App\Models\Campaign;
use App\Models\CampaignAdSet;
use App\Models\PlatformLocation;
use RuntimeException;

/** Review one published place change without changing local or provider state. */
class PublishedLocationChangePlanner
{
    public function __construct(
        private readonly PublishedLocationReadback $readback,
        private readonly TargetingSelections $selections,
    ) {}

    /** @return array<string, mixed> */
    public function preview(Campaign $campaign, string $operation, int $mappingId, int $expectedRevision, ?int $replacedMappingId = null): array
    {
        if (! $campaign->isPublished() || ! in_array($campaign->platform, ['meta', 'google'], true)) {
            throw new RuntimeException('Choose a published Meta or Google campaign before reviewing a location edit.');
        }

        if (! in_array($operation, ['add', 'remove', 'replace'], true)) {
            throw new RuntimeException('A published location edit must add, remove, or replace one selected city or region.');
        }

        $revision = (int) ($campaign->targetingSet()->value('revision') ?? 0);

        if ($revision !== $expectedRevision) {
            throw new RuntimeException('Targeting changed since it was opened. Review the latest selection and try again.');
        }

        $inspection = $this->readback->inspect($campaign);

        if ($inspection['status'] !== 'matches') {
            throw new RuntimeException('Provider location targeting differs from the saved baseline. Refresh and review the campaign before editing.');
        }

        $mapping = PlatformLocation::query()->with('location')->find($mappingId);
        $location = $mapping?->location;
        $countries = $this->selections->countries($campaign);

        if ($mapping === null || $location === null || $mapping->platform !== $campaign->platform
            || ! in_array($location->type, ['city', 'region'], true)
            || ! in_array($location->country_code, $countries, true)
            || blank($mapping->external_id) || $mapping->status !== 'verified'
            || ($campaign->platform === 'google' && ! preg_match('/^geoTargetConstants\/[0-9]+$/D', $mapping->external_id))
            || ($campaign->platform === 'meta' && ! preg_match('/^[0-9]+$/D', $mapping->external_id))
            || $mapping->verified_at === null || $mapping->verified_at->lt(now()->subDays(30))) {
            throw new RuntimeException('Choose a fresh, verified city or region within this campaign’s selected countries.');
        }

        $selected = $this->selections->reviewedCampaignPlaces($campaign);

        if ($campaign->platform === 'meta' && collect($selected)->contains(fn (array $place): bool => $place['kind'] === 'dma')) {
            throw new RuntimeException('This Meta campaign targets a market area. Review it before editing published city or region criteria.');
        }

        if ($campaign->platform === 'google' && collect($selected)->contains(fn (array $place): bool => in_array($place['kind'], ['dma', 'radius'], true))) {
            throw new RuntimeException('This Google campaign targets a DMA market or radius. Review it before editing published city or region criteria.');
        }

        $alreadySelected = collect($selected)->contains(fn (array $place): bool => $place['mapping_id'] === $mappingId);
        $replacedPlace = $operation === 'replace'
            ? collect($selected)->first(fn (array $place): bool => $place['mapping_id'] === $replacedMappingId)
            : null;

        if ($operation === 'replace' && ($replacedPlace === null || $alreadySelected
            || $replacedPlace['country_code'] !== $location->country_code
            || ! in_array($replacedPlace['kind'], ['city', 'region'], true))) {
            throw new RuntimeException('Choose a selected city or region and a different verified replacement in the same country.');
        }

        if (($operation === 'add' && $alreadySelected) || ($operation === 'remove' && ! $alreadySelected)) {
            throw new RuntimeException($operation === 'add' ? 'This city or region is already selected.'
                : 'This city or region is not selected on the published campaign.');
        }

        $otherPlacesInCountry = collect($selected)->contains(fn (array $place): bool => $place['country_code'] === $location->country_code
            && $place['mapping_id'] !== $mappingId);
        $before = $inspection['actual'];

        if ($campaign->platform === 'google' && filled($before['excluded_geo_targets'] ?? [])) {
            throw new RuntimeException('This Google campaign has location exclusions. Review them before editing included locations.');
        }

        $after = match (true) {
            $campaign->platform === 'meta' && $operation === 'replace' => $this->metaReplace($before, $mapping, $replacedPlace),
            $campaign->platform === 'google' && $operation === 'replace' => $this->googleReplace($before, $mapping, $replacedPlace),
            $campaign->platform === 'meta' => $this->metaAfter($before, $mapping, $operation, $otherPlacesInCountry),
            default => $this->googleAfter($before, $mapping, $operation, $otherPlacesInCountry),
        };

        $place = [
            'mapping_id' => $mapping->getKey(),
            'external_id' => $mapping->external_id,
            'parent_external_id' => $mapping->parent_external_id,
            'label' => $mapping->provider_name,
            'kind' => $location->type,
            'country_code' => $location->country_code,
        ];

        return [
            'campaign_id' => $campaign->getKey(),
            'platform' => $campaign->platform,
            'account_id' => $campaign->ad_account_id,
            'revision' => $revision,
            'operation' => $operation,
            'place' => $place,
            'replaced_place' => $replacedPlace,
            'before' => $before,
            'after' => $after,
            'baseline_hash' => hash('sha256', json_encode($campaign->published_state, JSON_THROW_ON_ERROR)),
            // The ad sets as well as the campaign row, because getAttributes()
            // stopped covering locations, audience, placements, optimization_goal,
            // conversion_event, starts_at and ends_at when they moved onto
            // campaign_ad_sets. Without them this fingerprint still matched after
            // the ad set's schedule, placements or optimisation goal had changed,
            // so an edit reviewed against one campaign was applied to another.
            // CampaignApprovalBinding::fingerprint() was updated for this and
            // this one was missed; the asymmetry is the evidence.
            'fingerprint' => hash('sha256', json_encode([
                $campaign->getAttributes(),
                $campaign->adSets()->get()->map(fn (CampaignAdSet $adSet): array => $adSet->getAttributes())->all(),
                $campaign->published_state, $revision,
                $operation, $place, $replacedPlace, $mapping->verified_at, $before, $after,
            ], JSON_THROW_ON_ERROR)),
        ];
    }

    /** @param array{countries: list<string>, cities: list<string>, regions: list<string>} $before
     * @param  array<string, mixed>  $replacedPlace
     * @return array{countries: list<string>, cities: list<string>, regions: list<string>}
     */
    private function metaReplace(array $before, PlatformLocation $mapping, array $replacedPlace): array
    {
        $oldKind = $replacedPlace['kind'] === 'city' ? 'cities' : 'regions';
        $newKind = $mapping->location->type === 'city' ? 'cities' : 'regions';
        $after = $before;
        $after[$oldKind] = array_values(array_diff($after[$oldKind], [$replacedPlace['external_id']]));
        $after[$newKind][] = $mapping->external_id;

        foreach (array_keys($after) as $kind) {
            $after[$kind] = array_values(array_unique($after[$kind]));
            sort($after[$kind]);
        }

        return $after;
    }

    /** @param array{geo_targets: list<string>} $before
     * @param  array<string, mixed>  $replacedPlace
     * @return array{geo_targets: list<string>}
     */
    private function googleReplace(array $before, PlatformLocation $mapping, array $replacedPlace): array
    {
        $after = array_values(array_diff($before['geo_targets'], [$replacedPlace['external_id']]));
        $after[] = $mapping->external_id;
        $after = array_values(array_unique($after));
        sort($after);

        return ['geo_targets' => $after];
    }

    /** @param array{countries: list<string>, cities: list<string>, regions: list<string>} $before
     * @return array{countries: list<string>, cities: list<string>, regions: list<string>}
     */
    private function metaAfter(array $before, PlatformLocation $mapping, string $operation, bool $otherPlacesInCountry): array
    {
        $kind = $mapping->location->type === 'city' ? 'cities' : 'regions';
        $after = $before;

        if ($operation === 'add') {
            $after[$kind][] = $mapping->external_id;

            if (! $otherPlacesInCountry) {
                $after['countries'] = array_values(array_diff($after['countries'], [$mapping->location->country_code]));
            }
        } else {
            $after[$kind] = array_values(array_diff($after[$kind], [$mapping->external_id]));

            if (! $otherPlacesInCountry) {
                $after['countries'][] = $mapping->location->country_code;
            }
        }

        foreach (array_keys($after) as $kind) {
            $after[$kind] = array_values(array_unique($after[$kind]));
            sort($after[$kind]);
        }

        return $after;
    }

    /** @param array{geo_targets: list<string>} $before
     * @return array{geo_targets: list<string>}
     */
    private function googleAfter(array $before, PlatformLocation $mapping, string $operation, bool $otherPlacesInCountry): array
    {
        $after = $before['geo_targets'];

        if ($operation === 'add') {
            if (! $otherPlacesInCountry) {
                $after = array_values(array_diff($after, [$this->googleCountryId($mapping->location->country_code)]));
            }

            $after[] = $mapping->external_id;
        } else {
            $after = array_values(array_diff($after, [$mapping->external_id]));

            if (! $otherPlacesInCountry) {
                $after[] = $this->googleCountryId($mapping->location->country_code);
            }
        }

        $after = array_values(array_unique($after));
        sort($after);

        return ['geo_targets' => $after];
    }

    private function googleCountryId(string $countryCode): string
    {
        $ids = PlatformLocation::query()->where('platform', 'google')
            ->where('status', 'verified')->whereNotNull('verified_at')
            ->where('verified_at', '>=', now()->subDays(30))
            ->whereHas('location', fn ($query) => $query->where('type', 'country')->where('iso_code', $countryCode))
            ->pluck('external_id')->all();

        if (count($ids) !== 1 || ! preg_match('/^geoTargetConstants\/[0-9]+$/D', $ids[0])) {
            throw new RuntimeException('The saved Google country mapping is missing or ambiguous. Verify it before editing locations.');
        }

        return $ids[0];
    }
}
