<?php

namespace App\Campaigns\Targeting;

use App\Campaigns\PendingChanges;
use App\Models\Campaign;
use App\Models\Location;
use App\Models\PlatformLocation;
use App\Models\TargetingSet;
use Illuminate\Support\Facades\DB;
use RuntimeException;

/** Save a confirmed provider edit without marking unrelated local changes as published. */
class PublishedLocationLocalCommitter
{
    public function __construct(
        private readonly PendingChanges $pendingChanges,
        private readonly TargetingSelections $selections,
    ) {}

    /** @param array<string, mixed> $plan */
    public function commit(Campaign $campaign, array $plan): Campaign
    {
        return DB::transaction(function () use ($campaign, $plan): Campaign {
            $locked = Campaign::query()->whereKey($campaign->getKey())->lockForUpdate()->firstOrFail();
            $set = TargetingSet::query()->where('campaign_id', $locked->getKey())->lockForUpdate()->first();
            $place = (array) ($plan['place'] ?? []);
            $mapping = PlatformLocation::query()->with('location')->find($place['mapping_id'] ?? 0);
            $location = $mapping?->location;

            if (! $locked->isPublished() || (int) ($plan['campaign_id'] ?? 0) !== (int) $locked->getKey()
                || ($plan['platform'] ?? null) !== $locked->platform
                || ($plan['account_id'] ?? null) !== $locked->ad_account_id
                || (int) ($plan['revision'] ?? -1) !== (int) ($set?->revision ?? 0)
                || ! is_string($plan['baseline_hash'] ?? null)
                || ! hash_equals($plan['baseline_hash'], hash('sha256', json_encode($locked->published_state, JSON_THROW_ON_ERROR)))
                || $mapping === null || $location === null || $mapping->platform !== $locked->platform
                || ! in_array($location->type, ['city', 'region'], true)
                || $mapping->status !== 'verified' || $mapping->verified_at === null
                || $mapping->verified_at->lt(now()->subDays(30))
                || $mapping->external_id !== ($place['external_id'] ?? null)
                || $mapping->parent_external_id !== ($place['parent_external_id'] ?? null)
                || $mapping->provider_name !== ($place['label'] ?? null)
                || $location->type !== ($place['kind'] ?? null)
                || $location->country_code !== ($place['country_code'] ?? null)) {
                throw new RuntimeException('Local targeting changed after provider confirmation. Reconcile this campaign before editing again.');
            }

            $countries = $this->selections->countries($locked);

            if (! in_array($location->country_code, $countries, true)) {
                throw new RuntimeException('The selected country changed after provider confirmation. Reconcile this campaign before editing again.');
            }

            $selected = $set?->locations()->where('location_id', $location->getKey())
                ->where('operation', 'include')->first();
            $operation = $plan['operation'] ?? null;
            $replacedPlace = (array) ($plan['replaced_place'] ?? []);
            $replacedSelection = $operation === 'replace'
                ? $set?->locations()->where('platform_location_id', $replacedPlace['mapping_id'] ?? 0)
                    ->where('operation', 'include')->first()
                : null;
            $replacedMapping = $replacedSelection?->platformLocation;

            if (! in_array($operation, ['add', 'remove', 'replace'], true)
                || ($operation === 'add' && $selected !== null)
                || ($operation === 'remove' && ($selected === null || $selected->platform_location_id !== $mapping->getKey()))
                || ($operation === 'replace' && ($selected !== null || $replacedSelection === null
                    || $replacedMapping === null
                    || $replacedMapping->external_id !== ($replacedPlace['external_id'] ?? null)
                    || $replacedMapping->parent_external_id !== ($replacedPlace['parent_external_id'] ?? null)
                    || $replacedSelection->kind !== ($replacedPlace['kind'] ?? null)
                    || $replacedSelection->country_code !== $location->country_code
                    || $replacedSelection->display_label !== ($replacedPlace['label'] ?? null)))) {
                throw new RuntimeException('The selected place changed after provider confirmation. Reconcile this campaign before editing again.');
            }

            $set ??= TargetingSet::query()->create([
                'campaign_id' => $locked->getKey(), 'platform' => $locked->platform,
                'mode' => 'override', 'revision' => 0, 'schema_version' => 1,
            ]);

            if ($set->wasRecentlyCreated || $set->mode !== 'override') {
                $selectedCountryIds = [];

                foreach ($countries as $code) {
                    $country = Location::query()->where('type', 'country')->where('iso_code', $code)->first();

                    if ($country === null) {
                        throw new RuntimeException('The selected country is missing from the local catalog. Reconcile this campaign before editing again.');
                    }

                    $selectedCountryIds[] = $country->getKey();
                    $set->locations()->updateOrCreate(
                        ['location_id' => $country->getKey(), 'operation' => 'include'],
                        ['kind' => 'country', 'country_code' => $code, 'display_label' => $country->name],
                    );
                }

                $set->locations()->where('kind', 'country')->where('operation', 'include')
                    ->whereNotIn('location_id', $selectedCountryIds)->delete();
            }

            if ($operation === 'replace') {
                $replacedSelection->delete();
            }

            if (in_array($operation, ['add', 'replace'], true)) {
                $set->locations()->create([
                    'location_id' => $location->getKey(),
                    'platform_location_id' => $mapping->getKey(),
                    'operation' => 'include',
                    'kind' => $location->type,
                    'display_label' => $mapping->provider_name,
                    'country_code' => $location->country_code,
                ]);
            } else {
                $selected->delete();
            }

            $options = (array) ($set->options ?? []);
            $options['place_intent_mode'] = 'override';
            $options['resolved_shared_places'] = [];
            $set->update(['mode' => 'override', 'revision' => $set->revision + 1, 'options' => $options]);

            $locked->unsetRelation('targetingSet');
            $snapshot = $this->pendingChanges->snapshot($locked);
            $published = (array) ($locked->published_state ?? []);
            $published['locations'] = $snapshot['locations'];
            $published['targeting_locations'] = $snapshot['targeting_locations'];
            $locked->update(['published_state' => $published, 'last_synced_at' => now(), 'last_error' => null]);

            return $locked->fresh();
        });
    }
}
