<?php

namespace App\Campaigns;

use App\Models\Campaign;
use App\Models\CampaignAd;
use App\Models\CampaignAdSet;
use Illuminate\Support\Collection;
use RuntimeException;

/**
 * Records a Meta copy of an ad set that is already in this campaign.
 *
 * Meta's /{ad_set_id}/copies endpoint copies the ad set and, with deep_copy,
 * its ads. The targeting stays on Meta. This class only chooses which ad set
 * was meant and stores the ids Meta returns.
 */
class AdSetDuplicator
{
    /**
     * @return array<string, mixed>
     */
    public function prepare(Campaign $campaign, ?string $adSetId): array
    {
        $published = $campaign->adSets()->whereNotNull('external_adset_id')->orderBy('position')->get();

        if ($published->isEmpty()) {
            return [
                'ok' => false,
                'error' => 'This campaign has no published ad set to duplicate.',
                'note' => 'Ask the user to publish the campaign first. Do not invent an ad set.',
            ];
        }

        $source = $this->source($published, $adSetId);

        if ($source === null) {
            return [
                'ok' => false,
                'ask' => 'Which ad set should be duplicated into this campaign?',
                'ad_sets' => $published->map(fn (CampaignAdSet $adSet): array => [
                    'id' => $adSet->id,
                    'external_adset_id' => $adSet->external_adset_id,
                    'name' => $adSet->name,
                ])->values()->all(),
                'note' => 'Ask the user which ad set to copy, then call this again with ad_set_id. '
                    .'The most recently created one is the last in this list. Do not say duplication is unavailable.',
            ];
        }

        return ['ok' => true, 'source' => $source];
    }

    /**
     * @param  array<string, mixed>  $copied  Meta's copies response
     * @param  list<array<string, mixed>>  $copiedAds  ads now under the new ad set, when the response did not name them
     */
    public function remember(Campaign $campaign, CampaignAdSet $source, array $copied, array $copiedAds, ?string $name, ?string $pixelId = null): CampaignAdSet
    {
        $adSetId = $this->copiedAdSetId($copied);

        if ($adSetId === '') {
            throw new RuntimeException('Meta did not return the copied ad set id.');
        }

        $position = ((int) $campaign->adSets()->max('position')) + 1;
        $copy = $campaign->adSets()->create([
            'position' => $position,
            'name' => filled($name) ? $name : $source->name.' - copy',
            'locations' => $source->locations,
            'audience' => [
                ...(array) ($source->audience ?? []),
                'duplicate_of' => (string) $source->external_adset_id,
                ...filled($pixelId) ? ['pixel_id' => $pixelId] : [],
            ],
            'placements' => $source->placements ?? $campaign->placements,
            'optimization_goal' => $source->optimization_goal,
            'conversion_event' => $source->conversion_event,
            'budget' => $source->budget,
            'budget_mode' => $source->budget_mode,
            'bid_strategy' => $source->bid_strategy,
            'bid_amount' => $source->bid_amount,
            'starts_at' => $source->starts_at,
            'ends_at' => $source->ends_at,
            'external_adset_id' => $adSetId,
            'status' => 'published',
        ]);

        $this->copyAds($campaign, $source, $copy, $this->adIds($copied, $copiedAds));

        return $copy;
    }

    /**
     * Store a copy whose source ad set is not a row here.
     *
     * Meta already copied the targeting. The local row only exists so the
     * destination campaign's panel can see the new ad set.
     *
     * @param  array<string, mixed>  $copied
     */
    public function rememberExternal(Campaign $campaign, string $sourceExternalId, array $copied, ?string $name): CampaignAdSet
    {
        $adSetId = $this->copiedAdSetId($copied);

        if ($adSetId === '') {
            throw new RuntimeException('Meta did not return the copied ad set id.');
        }

        $position = ((int) $campaign->adSets()->max('position')) + 1;
        $copy = $campaign->adSets()->create([
            'position' => $position,
            'name' => filled($name) ? $name : 'Ad set - copy',
            'locations' => ['countries' => []],
            'audience' => ['duplicate_of' => $sourceExternalId],
            'external_adset_id' => $adSetId,
            'status' => 'published',
        ]);

        foreach ($this->adIds($copied, []) as $match) {
            if (blank($match['ad_id'] ?? null)) {
                continue;
            }

            CampaignAd::create([
                'campaign_id' => $campaign->id,
                'ad_set_id' => $copy->id,
                'headline' => 'Ad',
                'primary_text' => '',
                'external_ad_id' => $match['ad_id'],
                'status' => 'published',
            ]);
        }

        return $copy;
    }

    /**
     * @param  Collection<int, CampaignAdSet>  $published
     */
    private function source(Collection $published, ?string $adSetId): ?CampaignAdSet
    {
        $adSetId = trim((string) $adSetId);

        if ($adSetId === '') {
            return $published->count() === 1 ? $published->first() : null;
        }

        return $published->first(fn (CampaignAdSet $adSet): bool => (string) $adSet->id === $adSetId
            || (string) $adSet->external_adset_id === $adSetId);
    }

    /** @param  array<string, mixed>  $copied */
    private function copiedAdSetId(array $copied): string
    {
        if (filled($copied['copied_adset_id'] ?? null)) {
            return (string) $copied['copied_adset_id'];
        }

        foreach ((array) ($copied['ad_object_ids'] ?? []) as $object) {
            if (is_array($object) && ($object['ad_object_type'] ?? null) === 'ad_set' && filled($object['copied_id'] ?? null)) {
                return (string) $object['copied_id'];
            }
        }

        return filled($copied['id'] ?? null) ? (string) $copied['id'] : '';
    }

    /**
     * @param  array<string, mixed>  $copied
     * @param  list<array<string, mixed>>  $copiedAds
     * @return array<string, array{ad_id: string, creative_id: ?string}>
     */
    private function adIds(array $copied, array $copiedAds): array
    {
        $ids = [];

        foreach ((array) ($copied['ad_object_ids'] ?? []) as $object) {
            if (! is_array($object) || ($object['ad_object_type'] ?? null) !== 'ad' || blank($object['copied_id'] ?? null)) {
                continue;
            }

            $ids[(string) ($object['source_id'] ?? '')] = [
                'ad_id' => (string) $object['copied_id'],
                'creative_id' => null,
            ];
        }

        if ($ids !== []) {
            return $ids;
        }

        foreach ($copiedAds as $ad) {
            if (blank($ad['id'] ?? null)) {
                continue;
            }

            $ids[] = [
                'ad_id' => (string) $ad['id'],
                'creative_id' => filled($ad['creative']['id'] ?? null) ? (string) $ad['creative']['id'] : null,
            ];
        }

        return $ids;
    }

    /**
     * @param  array<int|string, array{ad_id: string, creative_id: ?string}>  $copiedAds
     */
    private function copyAds(Campaign $campaign, CampaignAdSet $source, CampaignAdSet $copy, array $copiedAds): int
    {
        $home = $source->campaign;
        $ads = $home->ads()
            ->where(function ($query) use ($home, $source): void {
                $query->where('ad_set_id', $source->id);

                if ($source->is($home->primaryAdSet)) {
                    $query->orWhereNull('ad_set_id');
                }
            })
            ->orderBy('id')
            ->get()
            ->values();

        foreach ($ads as $index => $ad) {
            $match = $copiedAds[(string) $ad->external_ad_id] ?? $copiedAds[$index] ?? null;

            CampaignAd::create([
                'campaign_id' => $campaign->id,
                'ad_set_id' => $copy->id,
                'asset_id' => $ad->asset_id,
                'headline' => $ad->headline,
                'primary_text' => $ad->primary_text,
                'description' => $ad->description,
                'cta' => $ad->cta,
                'external_ad_id' => $match['ad_id'] ?? null,
                'external_creative_id' => $match['creative_id'] ?? null,
                'status' => $match === null ? 'draft' : 'published',
            ]);
        }

        return $ads->count();
    }
}
