<?php

namespace App\Campaigns;

use App\Campaigns\Platforms\Platforms;
use App\Campaigns\Targeting\GoogleUserListSelections;
use App\Campaigns\Targeting\LinkedInAudienceSelections;
use App\Campaigns\Targeting\MetaAudienceSelections;
use App\Campaigns\Targeting\SearchKeywordSelections;
use App\Models\Campaign;

/**
 * The difference between what we hold and what the platform holds.
 *
 * Editing a live campaign used to update our copy and nothing else: the
 * platform kept the old values, the screen showed the new ones, and nothing
 * said they disagreed. Comparing against published_state, which is what was
 * last sent, is what makes that visible.
 *
 * Changes are split in two because platforms treat them differently. Budget and
 * schedule can be updated in place. An ad's creative cannot: Meta treats it as
 * immutable, so changing a headline means building a new creative and a new ad
 * and retiring the old one. Presenting both as "an edit" hides work that
 * behaves nothing alike.
 */
class PendingChanges
{
    /**
     * Where the column name is not what to say to a person.
     *
     * "utm cannot be changed after publishing" tells a buyer nothing about
     * what they would have to redo.
     *
     * @var array<string, string>
     */
    private const LABELS = [
        'utm' => 'click tracking is part of the destination URL, so changing it needs a new creative and a new ad',
        'budget_level' => 'a budget cannot be moved between the campaign and the ad set after publishing',
        'budget_mode' => 'a daily budget cannot become a lifetime one after publishing',
    ];

    public function __construct(
        private readonly Platforms $platforms,
        private readonly SearchKeywordSelections $searchKeywords,
        private readonly GoogleUserListSelections $userLists,
        private readonly MetaAudienceSelections $metaAudiences,
        private readonly LinkedInAudienceSelections $linkedinAudiences,
    ) {}

    /**
     * Fields changed since publish that the platform can update in place.
     *
     * @return array<string, array{from: mixed, to: mixed}>
     */
    public function updatable(Campaign $campaign): array
    {
        if (! $campaign->isPublished()) {
            return [];
        }

        $published = (array) ($campaign->published_state ?? []);
        $editable = $this->platforms->for($campaign)->editableAfterPublish();
        $changes = [];

        foreach ($editable as $field) {
            $now = $this->normalise($campaign->getAttribute($field));
            $then = $this->normalise($published[$field] ?? null);

            if (! $this->sameSnapshotValue($now, $then)) {
                $changes[$field] = ['from' => $then, 'to' => $now];
            }
        }

        return $changes;
    }

    /**
     * Changes that cannot be an update, and need the ad rebuilding instead.
     *
     * @return list<string>
     */
    public function requiringRebuild(Campaign $campaign): array
    {
        if (! $campaign->isPublished()) {
            return [];
        }

        $published = (array) ($campaign->published_state ?? []);
        $problems = [];

        if ($this->adsFingerprint($campaign) !== ($published['ads_fingerprint'] ?? null)) {
            // Only true off Meta now. edit_entity puts new copy on a live Meta
            // ad by pointing it at a new creative, keeping the ad and its
            // history; naming a rebuild here would send a buyer the long way
            // round for something one call does.
            $problems[] = $campaign->platform === 'meta'
                ? 'ad copy or creative changed, which edit_entity applies to the live ad'
                : 'ad copy or creative changed, which needs a new creative and a new ad';
        }

        // These are set at creation and cannot move afterwards on any platform
        // we support. Changing one means a new campaign, not an edit.
        // budget_level and budget_mode included: Meta will change the amount on
        // a running campaign but not move it between the campaign and the ad
        // set, nor turn a daily budget into a lifetime one.
        foreach (['objective', 'ad_account_id', 'page_id', 'pixel_id', 'landing_url', 'utm', 'budget_level', 'budget_mode'] as $field) {
            $now = $this->normalise($campaign->getAttribute($field));
            $then = $this->normalise($published[$field] ?? null);

            if ($then !== null && ! $this->sameSnapshotValue($now, $then)) {
                $problems[] = self::LABELS[$field] ?? str_replace('_', ' ', $field)
                    .' cannot be changed after publishing';
            }
        }

        if (array_key_exists('locations', $published) && ! $this->sameSnapshotValue($this->normalise($campaign->locations), $published['locations'])) {
            $problems[] = 'location targeting changed, which needs a new campaign';
        }

        if (array_key_exists('targeting_locations', $published) && ! $this->sameSnapshotValue($this->targetingLocations($campaign), $published['targeting_locations'])) {
            $problems[] = 'city or region targeting changed, which needs a new campaign';
        }

        if (array_key_exists('positive_geo_target_type', $published)
            && $campaign->platform === 'google'
            && ($campaign->targetingSet()->first()?->options['google_presence'] ?? 'PRESENCE') !== $published['positive_geo_target_type']) {
            $problems[] = 'Google location presence preference changed, which needs a new campaign';
        }

        if (array_key_exists('search_keywords', $published)
            && $campaign->platform === 'google'
            && ! $this->sameSnapshotValue($this->searchKeywords->criteria($campaign), $published['search_keywords'])) {
            $problems[] = 'Google Search keywords changed, which needs a new campaign';
        }

        if (array_key_exists('google_user_lists', $published)
            && $campaign->platform === 'google'
            && ! $this->sameSnapshotValue($this->userLists->selected($campaign), $published['google_user_lists'])) {
            $problems[] = 'Google audience lists changed, which needs a new campaign';
        }

        if (array_key_exists('meta_audiences', $published)
            && $campaign->platform === 'meta'
            && ! $this->sameSnapshotValue($this->metaAudiences->selected($campaign), $published['meta_audiences'])) {
            $problems[] = 'Meta website audiences changed, which needs a new campaign';
        }

        if (array_key_exists('linkedin_segments', $published)
            && $campaign->platform === 'linkedin'
            && ! $this->sameSnapshotValue($this->linkedinAudiences->selected($campaign), $published['linkedin_segments'])) {
            $problems[] = 'LinkedIn retargeting segments changed, which needs a new campaign';
        }

        if (array_key_exists('google_imported_ad_group_criteria', $published)
            && ! $this->sameSnapshotValue($campaign->external_ids['google_ad_group_criteria'] ?? null, $published['google_imported_ad_group_criteria'])) {
            $problems[] = 'imported Google Search criteria changed, which needs a fresh provider import';
        }

        if (array_key_exists('meta_imported_custom_audience_criteria', $published)
            && ! $this->sameSnapshotValue($campaign->external_ids['meta_custom_audience_criteria'] ?? null, $published['meta_imported_custom_audience_criteria'])) {
            $problems[] = 'imported Meta audience criteria changed, which needs a fresh provider import';
        }

        return $problems;
    }

    public function any(Campaign $campaign): bool
    {
        return $this->updatable($campaign) !== [] || $this->requiringRebuild($campaign) !== [];
    }

    /**
     * What to store as the platform's current state once a publish or update
     * succeeds.
     *
     * @return array<string, mixed>
     */
    public function snapshot(Campaign $campaign): array
    {
        $fields = [
            ...$this->platforms->for($campaign)->editableAfterPublish(),
            'objective', 'ad_account_id', 'page_id', 'pixel_id', 'landing_url', 'utm',
            'budget_level', 'budget_mode',
        ];

        $state = [];

        foreach (array_unique($fields) as $field) {
            $state[$field] = $this->normalise($campaign->getAttribute($field));
        }

        $state['ads_fingerprint'] = $this->adsFingerprint($campaign);
        $state['locations'] = $this->normalise($campaign->locations);
        $state['targeting_locations'] = $this->targetingLocations($campaign);

        if ($campaign->platform === 'google' && ($campaign->campaign_type ?: 'search') === 'search') {
            $keywords = $this->searchKeywords->criteria($campaign);

            if ($keywords !== []) {
                $state['search_keywords'] = $keywords;
            }
        }

        if ($campaign->platform === 'google' && $this->userLists->selected($campaign) !== []) {
            $state['google_user_lists'] = $this->userLists->selected($campaign);
        }

        if ($campaign->platform === 'meta' && $this->metaAudiences->selected($campaign) !== []) {
            $state['meta_audiences'] = $this->metaAudiences->selected($campaign);
        }

        if ($campaign->platform === 'linkedin' && $this->linkedinAudiences->selected($campaign) !== []) {
            $state['linkedin_segments'] = $this->linkedinAudiences->selected($campaign);
        }

        if ($campaign->platform === 'google' && array_key_exists('google_ad_group_criteria', (array) $campaign->external_ids)) {
            $state['google_imported_ad_group_criteria'] = $campaign->external_ids['google_ad_group_criteria'];
        }

        if ($campaign->platform === 'meta' && array_key_exists('meta_custom_audience_criteria', (array) $campaign->external_ids)) {
            $state['meta_imported_custom_audience_criteria'] = $campaign->external_ids['meta_custom_audience_criteria'];
        }

        if ($campaign->platform === 'google'
            && isset($campaign->targetingSet()->first()?->options['google_presence'])) {
            $state['positive_geo_target_type'] = $campaign->targetingSet()->first()->options['google_presence'];
        }

        return $state;
    }

    /** @return list<array{kind: string, operation: string, country_code: string|null, external_id: string|null, latitude: string|null, longitude: string|null, radius: string|null, radius_unit: string|null}> */
    private function targetingLocations(Campaign $campaign): array
    {
        return $campaign->targetingSet?->locations()
            ->where('kind', '!=', 'country')
            ->with('platformLocation:id,external_id')
            ->orderBy('id')
            ->get()
            ->map(fn ($selection): array => [
                'kind' => $selection->kind,
                'operation' => $selection->operation,
                'country_code' => $selection->country_code,
                'external_id' => $selection->platformLocation?->external_id,
                'latitude' => $selection->latitude,
                'longitude' => $selection->longitude,
                'radius' => $selection->radius,
                'radius_unit' => $selection->radius_unit,
            ])
            ->all() ?? [];
    }

    /**
     * A stable summary of every ad's words and image.
     *
     * Cheaper and clearer than diffing rows: any change to copy or creative
     * changes the fingerprint, and that is the only question being asked.
     */
    private function adsFingerprint(Campaign $campaign): string
    {
        return hash('sha256', $campaign->ads()->orderBy('id')->get()
            ->map(fn ($ad): string => implode('|', [
                $ad->headline, $ad->primary_text, (string) $ad->description, $ad->cta, (string) $ad->asset_id,
            ]))
            ->implode("\n"));
    }

    /** Dates and decimals compare badly across a JSON round trip. */
    private function normalise(mixed $value): mixed
    {
        return match (true) {
            $value instanceof \DateTimeInterface => $value->format('Y-m-d H:i:s'),
            is_numeric($value) => (string) $value,
            default => $value,
        };
    }

    /** Compare JSON objects without depending on database key order. */
    private function sameSnapshotValue(mixed $current, mixed $published): bool
    {
        return $this->normaliseSnapshotValue($current) === $this->normaliseSnapshotValue($published);
    }

    private function normaliseSnapshotValue(mixed $value): mixed
    {
        if (! is_array($value)) {
            return $value;
        }

        foreach ($value as $key => $entry) {
            $value[$key] = $this->normaliseSnapshotValue($entry);
        }

        if (! array_is_list($value)) {
            ksort($value);
        }

        return $value;
    }
}
