<?php

namespace App\Campaigns;

use App\Campaigns\Targeting\TargetingSelections;
use App\Models\Brief;
use App\Models\Campaign;
use App\Models\TargetingSet;
use App\Models\User;
use Illuminate\Support\Facades\DB;
use RuntimeException;

/** Copies a local campaign into a separate draft without provider delivery state. */
class CampaignDuplicator
{
    private const AD_SET_FIELDS = [
        'position', 'name', 'locations', 'audience', 'placements',
        'optimization_goal', 'conversion_event', 'budget', 'budget_mode',
        'bid_strategy', 'bid_amount', 'starts_at', 'ends_at',
    ];

    public function __construct(private readonly TargetingSelections $selections) {}

    public function duplicate(Campaign $source, User $owner, ?string $conversationId, string $name): Campaign
    {
        if ((string) $source->user_id !== (string) $owner->getKey()
            || ($source->brief !== null && (string) $source->brief->user_id !== (string) $owner->getKey())) {
            throw new RuntimeException('This campaign does not belong to the signed-in user.');
        }

        if (blank($name) || mb_strlen($name) > 255) {
            throw new RuntimeException('Choose a campaign name between 1 and 255 characters.');
        }

        $importedCriteria = (array) ($source->external_ids ?? []);
        $sourceAdSets = $source->adSets()->get();

        if (filled($source->meta['linkedin_import']['targetingCriteria'] ?? null)) {
            throw new RuntimeException('This imported LinkedIn campaign contains provider targeting that cannot yet be copied faithfully. Review and rebuild those selections in a new draft.');
        }

        if ($sourceAdSets->isEmpty()) {
            throw new RuntimeException('This campaign has no ad set to copy.');
        }

        if ($sourceAdSets->contains(function ($adSet): bool {
            $locations = (array) ($adSet->locations ?? []);

            return filled($locations['meta_geo_locations'] ?? null)
                || filled($locations['google_location_criteria'] ?? null)
                || filled($locations['google_proximity_criteria'] ?? null);
        })
            || filled($importedCriteria['meta_custom_audience_criteria'] ?? null)
            || filled($importedCriteria['google_ad_group_criteria'] ?? null)) {
            throw new RuntimeException('This imported campaign contains provider targeting that cannot be copied faithfully. Review and rebuild those selections in a new draft.');
        }

        return DB::transaction(function () use ($source, $owner, $conversationId, $name, $sourceAdSets): Campaign {
            $brief = Brief::query()->create([
                'user_id' => $owner->getKey(),
                'conversation_id' => $conversationId,
                'landing_url' => $source->landing_url,
                'promoting' => $source->brief?->promoting,
                'outcome' => $source->brief?->outcome,
                'locations' => ['countries' => $this->selections->countries($source)],
                'budget' => $source->budget,
                'budget_mode' => $source->budget_mode,
                'currency' => $source->currency,
                'starts_at' => $source->brief?->starts_at,
                'ends_at' => $source->brief?->ends_at,
                'page_analysis' => $source->brief?->page_analysis,
            ]);

            $briefLocationIds = $this->copyTargetingSet($source->brief?->targetingSet, $brief, 'brief_id');

            $copy = $source->replicate([
                'user_id', 'brief_id', 'name', 'status', 'external_campaign_id',
                'external_ids', 'published_state', 'activated_at', 'last_synced_at', 'last_error',
            ]);
            $copy->user_id = $owner->getKey();
            $copy->brief_id = $brief->getKey();
            $copy->name = $name;
            $copy->status = 'draft';
            $copy->budget = $source->budget;
            $copy->budget_mode = $source->budget_mode;
            $copy->landing_url = $source->landing_url;
            $copy->save();

            $adSetIds = [];

            foreach ($sourceAdSets as $index => $sourceAdSet) {
                $attributes = $sourceAdSet->only(self::AD_SET_FIELDS);
                $attributes['name'] = $index === 0 && $sourceAdSet->name === $source->name.' - ad set'
                    ? $name.' - ad set' : $sourceAdSet->name;
                $attributes['status'] = 'draft';

                $adSet = $index === 0 ? $copy->primaryAdSet : $copy->adSets()->make();
                $adSet->fill($attributes);
                $adSet->campaign_id = $copy->getKey();
                $adSet->save();
                $adSetIds[$sourceAdSet->getKey()] = $adSet->getKey();
            }

            $this->copyTargetingSet($source->targetingSet, $copy, 'campaign_id', $briefLocationIds);

            foreach ($source->ads()->get() as $ad) {
                $adSetId = $ad->ad_set_id === null
                    ? $adSetIds[$sourceAdSets->first()->getKey()]
                    : ($adSetIds[$ad->ad_set_id] ?? null);

                if ($adSetId === null) {
                    throw new RuntimeException('An ad belongs to an ad set that cannot be copied.');
                }

                $copy->ads()->create([
                    ...$ad->only(['asset_id', 'headline', 'primary_text', 'description', 'cta']),
                    'ad_set_id' => $adSetId,
                    'status' => 'draft',
                ]);
            }

            foreach ($source->campaignCreatives()->get() as $creative) {
                $copy->campaignCreatives()->create([
                    ...$creative->only(['creative_id', 'ad_copy_id']),
                    'status' => 'draft',
                ]);
            }

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

    /** @return array<int, int> Old location row IDs to new IDs. */
    private function copyTargetingSet(?TargetingSet $source, Brief|Campaign $owner, string $ownerColumn, array $briefLocationIds = []): array
    {
        if ($source === null) {
            return [];
        }

        $copy = $source->replicate(['brief_id', 'campaign_id']);
        $copy->{$ownerColumn} = $owner->getKey();
        $copy->save();
        $locationIds = [];

        foreach ($source->locations()->get() as $location) {
            $copiedLocation = $location->replicate(['targeting_set_id']);
            $copiedLocation->targeting_set_id = $copy->getKey();
            $copiedLocation->save();
            $locationIds[$location->getKey()] = $copiedLocation->getKey();
        }

        if ($owner instanceof Campaign) {
            $options = (array) ($copy->options ?? []);
            $resolved = (array) ($options['resolved_shared_places'] ?? []);
            $options['resolved_shared_places'] = [];

            foreach ($resolved as $oldBriefLocationId => $platformLocationId) {
                if (! isset($briefLocationIds[$oldBriefLocationId])) {
                    throw new RuntimeException('A saved shared place no longer has its original brief location. Review targeting before duplicating.');
                }

                $options['resolved_shared_places'][$briefLocationIds[$oldBriefLocationId]] = $platformLocationId;
            }

            if ($resolved !== []) {
                $copy->update(['options' => $options]);
            }
        }

        return $locationIds;
    }
}
