<?php

namespace App\Campaigns\Targeting;

use App\Models\Campaign;
use App\Models\Decision;
use Illuminate\Support\Facades\Cache;
use RuntimeException;
use Throwable;

/** Serialize and record a reviewed edit across provider and local state. */
class PublishedLocationEditor
{
    public function __construct(
        private readonly PublishedLocationChangePlanner $planner,
        private readonly PublishedLocationProviderMutator $provider,
        private readonly PublishedLocationLocalCommitter $local,
    ) {}

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

        if ($decision->action !== 'edit_published_location' || $decision->state !== 'consumed'
            || (string) $decision->subject_id !== (string) $campaign->getKey()
            || (int) ($plan['campaign_id'] ?? 0) !== (int) $campaign->getKey()) {
            throw new RuntimeException('This published-location edit has no matching consumed approval.');
        }

        $lock = Cache::lock('published-location-edit:'.$campaign->getKey(), 600);

        if (! $lock->get()) {
            $decision->update(['state' => 'blocked', 'reason' => 'Another location edit is in progress. Review the campaign again.']);

            throw new RuntimeException('Another location edit is in progress. Review the campaign again.');
        }

        $providerConfirmed = false;

        try {
            $storedDecision = Decision::query()->whereKey($decision->getKey())->first();

            if ($storedDecision?->state !== 'consumed'
                || ($storedDecision->params['plan']['fingerprint'] ?? null) !== ($plan['fingerprint'] ?? null)) {
                throw new RuntimeException('This location approval was already used or its reviewed plan changed. Review the edit again.');
            }

            $fresh = $campaign->fresh();
            $current = ($plan['operation'] ?? null) === 'replace'
                ? $this->planner->preview(
                    $fresh, 'replace', (int) $plan['place']['mapping_id'],
                    (int) $plan['revision'], (int) $plan['replaced_place']['mapping_id'],
                )
                : $this->planner->preview(
                    $fresh, (string) $plan['operation'],
                    (int) $plan['place']['mapping_id'], (int) $plan['revision'],
                );

            if (! hash_equals((string) $plan['fingerprint'], (string) $current['fingerprint'])) {
                throw new RuntimeException('Campaign or provider locations changed after approval. Review the edit again.');
            }

            $confirmed = $this->provider->apply($fresh, $current);
            $providerConfirmed = true;
            $saved = $this->local->commit($fresh, $current);
            $result = [
                'campaign_id' => $saved->getKey(),
                'operation' => $current['operation'],
                'place' => $current['place'],
                'replaced_place' => $current['replaced_place'] ?? null,
                'provider_locations' => $confirmed['actual'],
                'targeting_revision' => $saved->targetingSet()->value('revision'),
            ];
            $decision->update(['state' => 'applied', 'result' => $result, 'applied_at' => now()]);

            return $result;
        } catch (Throwable $exception) {
            if ($providerConfirmed || $exception instanceof PublishedLocationReconciliationRequired) {
                $campaign->fresh()->update(['last_error' => 'Published-location reconciliation required: '.$exception->getMessage()]);
            }

            Decision::query()->whereKey($decision->getKey())->where('state', 'consumed')
                ->update(['state' => 'blocked', 'reason' => $exception->getMessage()]);

            throw $exception;
        } finally {
            $lock->release();
        }
    }
}
