<?php

namespace App\Campaigns\Targeting;

use App\Models\Campaign;
use App\Models\GoogleAdsConnection;
use App\Services\GoogleAdsService;
use App\Services\Meta\GraphApi;
use App\Services\Meta\Meta;
use RuntimeException;
use Throwable;

/** Provider write adapter; the chat registers its approved caller only when enabled. */
class PublishedLocationProviderMutator
{
    public function __construct(
        private readonly PublishedLocationReadback $readback,
        private readonly Meta $meta,
        private readonly GraphApi $graph,
        private readonly GoogleAdsService $google,
    ) {}

    /** @param array<string, mixed> $plan
     * @return array<string, mixed>
     */
    public function apply(Campaign $campaign, array $plan): array
    {
        if (! config('platforms.guardrails.published_location_edits_enabled', false)) {
            throw new RuntimeException('Published location edits are disabled until paused-provider validation is complete.');
        }

        if (! $campaign->isPublished() || ! in_array($campaign->platform, ['meta', 'google'], true)
            || (int) ($plan['campaign_id'] ?? 0) !== (int) $campaign->getKey()
            || ($plan['platform'] ?? null) !== $campaign->platform
            || ($plan['account_id'] ?? null) !== $campaign->ad_account_id) {
            throw new RuntimeException('The approved location plan does not belong to this published campaign and account.');
        }

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

        if ($inspection['status'] !== 'matches' || ! $this->sameLocations($inspection['actual'], $plan['before'] ?? null)) {
            throw new RuntimeException('Provider locations changed since approval. Review the current campaign again.');
        }

        if ($campaign->platform === 'meta') {
            $this->metaApply($campaign, $plan);
        } else {
            $this->googleApply($campaign, $plan);
        }

        try {
            $confirmed = $this->readback->inspect($campaign);
        } catch (Throwable $exception) {
            throw new PublishedLocationReconciliationRequired(
                'The provider edit may have succeeded, but its new locations could not be confirmed. Reconcile this campaign before editing again.',
                previous: $exception,
            );
        }

        if (! $this->sameLocations($confirmed['actual'], $plan['after'] ?? null)) {
            throw new PublishedLocationReconciliationRequired('The provider returned different location targeting after the edit. Local targeting was not changed; reconcile this campaign before editing again.');
        }

        return $confirmed;
    }

    /** @param array<string, mixed> $plan */
    private function metaApply(Campaign $campaign, array $plan): void
    {
        $accountId = $this->meta->campaignAccountId((string) $campaign->external_campaign_id);

        if ('act_'.preg_replace('/^act_/', '', (string) $accountId) !== $campaign->ad_account_id) {
            throw new RuntimeException('This Meta campaign belongs to a different ad account.');
        }

        $adSets = $this->meta->adSets((string) $campaign->external_campaign_id, $campaign->ad_account_id, fresh: true);
        $adSetId = (string) ($campaign->external_ids['adset_id'] ?? '');

        if (count($adSets) !== 1 || $adSetId === '' || (string) ($adSets[0]['id'] ?? '') !== $adSetId
            || filled($campaign->external_ids['other_adset_ids'] ?? null)
            || ! is_array($adSets[0]['targeting'] ?? null)
            || ! is_array(data_get($adSets[0], 'targeting.geo_locations'))) {
            throw new RuntimeException('Meta returned a different ad set or incomplete targeting. Review it before editing.');
        }

        $targeting = $adSets[0]['targeting'];
        $geo = $targeting['geo_locations'];

        if (! $this->sameLocations($this->readback->normaliseMeta($geo), $plan['before'])) {
            throw new RuntimeException('Meta location targeting changed after readback. Review it again.');
        }

        foreach (['countries', 'cities', 'regions'] as $kind) {
            $wanted = $plan['after'][$kind] ?? null;

            if (! is_array($wanted)) {
                throw new RuntimeException('The approved Meta location plan is incomplete.');
            }

            if ($kind === 'countries') {
                $entries = $wanted;
            } else {
                $existing = collect($geo[$kind] ?? [])->keyBy(fn (array $entry): string => (string) $entry['key']);
                $entries = array_map(fn (string $id): array => $existing->get($id) ?? ['key' => $id], $wanted);
            }

            if ($entries === []) {
                unset($geo[$kind]);
            } else {
                $geo[$kind] = $entries;
            }
        }

        $targeting['geo_locations'] = $geo;
        try {
            $this->graph->updateEntity($adSetId, [
                'targeting' => json_encode($targeting, JSON_THROW_ON_ERROR),
            ], $campaign->ad_account_id);
        } catch (Throwable $exception) {
            throw new PublishedLocationReconciliationRequired(
                'Meta did not confirm whether the location edit was applied. Reconcile provider targeting before editing again.',
                previous: $exception,
            );
        }
    }

    /** @param array<string, mixed> $plan */
    private function googleApply(Campaign $campaign, array $plan): void
    {
        $connection = GoogleAdsConnection::shared()
            ?? throw new RuntimeException(GoogleAdsConnection::missingReason());

        // The campaign's own account; see PublishedLocationReadback for why
        // this adopts instead of refusing.
        $connection = $connection->onCustomer((string) $campaign->ad_account_id);

        $criteria = $this->google->readCampaignLocationCriteria(
            $connection, (string) $campaign->external_campaign_id, includeStatus: true, fresh: true,
        );
        $ids = array_column($criteria, 'geo_target');
        sort($ids);

        if ($ids !== ($plan['before']['geo_targets'] ?? null)) {
            throw new RuntimeException('Google location targeting changed after readback. Review it again.');
        }

        try {
            $this->google->replaceCampaignLocationCriteria(
                $connection, (string) $campaign->external_campaign_id, $criteria, $plan['after']['geo_targets'],
            );
        } catch (Throwable $exception) {
            throw new PublishedLocationReconciliationRequired(
                'Google did not confirm whether the location edit was applied. Reconcile provider targeting before editing again.',
                previous: $exception,
            );
        }
    }

    /** @param array<string, mixed>|null $reviewed */
    private function sameLocations(array $actual, ?array $reviewed): bool
    {
        if ($reviewed === null) {
            return false;
        }

        ksort($actual);
        ksort($reviewed);

        return $actual === $reviewed;
    }
}
