<?php

namespace App\Campaigns\Targeting;

use App\Models\Campaign;
use App\Models\TargetingSet;
use App\Services\Meta\Meta;
use Illuminate\Support\Facades\DB;
use RuntimeException;

class MetaAudienceSelections
{
    public function __construct(
        private readonly Meta $meta,
        private readonly TargetingSelections $locations,
    ) {}

    /** @return list<array<string, mixed>> */
    public function discover(Campaign $campaign, ?string $query = null): array
    {
        $account = $this->account($campaign);

        if ($query !== null && ! preg_match('/^[\pL\pN ._-]{2,60}$/uD', trim($query))) {
            throw new RuntimeException('Search for an audience name using 2 to 60 letters or numbers.');
        }

        $pixels = array_column($this->meta->pixels($account), 'id');
        $categoryEligible = (array) ($campaign->special_ad_categories ?? []) === ['NONE'];

        return collect($this->meta->customAudiences($account))
            ->filter(static fn (array $audience): bool => $query === null
                || str_contains(mb_strtolower((string) ($audience['name'] ?? '')), mb_strtolower(trim($query))))
            ->map(fn (array $audience): array => [
                'id' => (string) ($audience['id'] ?? ''),
                'name' => (string) ($audience['name'] ?? ''),
                'subtype' => (string) ($audience['subtype'] ?? ''),
                'pixel_id' => (string) ($audience['pixel_id'] ?? ''),
                'account_id' => $this->normaliseAccount((string) ($audience['account_id'] ?? '')),
                'available' => $categoryEligible && $this->eligible($audience, $account, $pixels),
            ])
            ->values()->all();
    }

    /** @return list<array{id: string, name: string, subtype: string, pixel_id: string, account_id: string, operation: string}> */
    public function selected(Campaign $campaign): array
    {
        $values = $campaign->targetingSet()->first()?->options['meta_audiences'] ?? [];

        if (! is_array($values)) {
            throw new RuntimeException('Saved Meta audiences are invalid. Review targeting.');
        }

        $account = $this->normaliseAccount((string) $campaign->ad_account_id);

        foreach ($values as $audience) {
            if (! is_array($audience)
                || ! preg_match('/^[0-9]+$/D', (string) ($audience['id'] ?? ''))
                || trim((string) ($audience['name'] ?? '')) === ''
                || ($audience['subtype'] ?? null) !== 'WEBSITE'
                || ! preg_match('/^[0-9]+$/D', (string) ($audience['pixel_id'] ?? ''))
                || ($audience['account_id'] ?? null) !== $account
                || ! in_array($audience['operation'] ?? null, ['include', 'exclude'], true)) {
                throw new RuntimeException('Saved Meta audience no longer matches this campaign and account.');
            }
        }

        return array_values($values);
    }

    /** @return list<array<string, mixed>> */
    public function verifiedForPublish(Campaign $campaign): array
    {
        $selected = $this->selected($campaign);

        if ($selected === []) {
            return [];
        }

        if ((array) ($campaign->special_ad_categories ?? []) !== ['NONE']) {
            throw new RuntimeException('Meta website audiences are unavailable for this declared special ad category.');
        }

        $account = $this->account($campaign);
        $pixels = array_column($this->meta->pixels($account, fresh: true), 'id');
        $remote = collect($this->meta->customAudiences($account, fresh: true));

        foreach ($selected as $audience) {
            $matches = $remote->where('id', $audience['id'])->values();

            if ($matches->count() !== 1 || ! $this->eligible($matches[0], $account, $pixels)
                || (string) $matches[0]['name'] !== $audience['name']
                || (string) $matches[0]['pixel_id'] !== $audience['pixel_id']) {
                throw new RuntimeException('A saved Meta website audience is unavailable or changed. Review it before publishing.');
            }
        }

        return $selected;
    }

    /** @return list<array<string, mixed>> */
    public function listSizes(Campaign $campaign): array
    {
        $selected = $this->selected($campaign);

        if ($selected === []) {
            return [];
        }

        if ((array) ($campaign->special_ad_categories ?? []) !== ['NONE']) {
            return array_map(static fn (array $audience): array => [
                'id' => $audience['id'], 'name' => $audience['name'], 'operation' => $audience['operation'],
                'status' => 'unavailable', 'metric' => 'estimated_meta_custom_audience_size_range',
                'lower_bound' => null, 'upper_bound' => null,
            ], $selected);
        }

        $account = $this->account($campaign);
        $pixels = array_column($this->meta->pixels($account, fresh: true), 'id');
        $remote = collect($this->meta->customAudiences($account, fresh: true));

        return array_map(function (array $audience) use ($account, $pixels, $remote): array {
            $match = $remote->where('id', $audience['id'])->values();
            $fresh = $match->count() === 1 ? $match[0] : null;
            $available = $fresh !== null && $this->eligible($fresh, $account, $pixels)
                && (string) $fresh['name'] === $audience['name']
                && (string) $fresh['pixel_id'] === $audience['pixel_id'];
            $lower = $available ? ($fresh['approximate_count_lower_bound'] ?? null) : null;
            $upper = $available ? ($fresh['approximate_count_upper_bound'] ?? null) : null;

            return [
                'id' => $audience['id'], 'name' => $audience['name'], 'operation' => $audience['operation'],
                'status' => is_numeric($lower) && is_numeric($upper) ? 'fresh' : 'unavailable',
                'metric' => 'estimated_meta_custom_audience_size_range',
                'lower_bound' => is_numeric($lower) ? (int) $lower : null,
                'upper_bound' => is_numeric($upper) ? (int) $upper : null,
            ];
        }, $selected);
    }

    public function save(Campaign $campaign, string $id, string $operation, int $expectedRevision): TargetingSet
    {
        $account = $this->account($campaign);

        if ($campaign->isPublished() || ! preg_match('/^[0-9]+$/D', $id)
            || ! in_array($operation, ['include', 'exclude'], true)) {
            throw new RuntimeException('Choose an include or exclude website audience on a draft Meta campaign.');
        }

        $match = collect($this->discover($campaign))->where('id', $id)->values();

        if ($match->count() !== 1 || ! $match[0]['available']) {
            throw new RuntimeException('This Meta website audience is unavailable for the campaign account.');
        }

        $countries = $this->locations->countries($campaign);

        if ($countries === []) {
            throw new RuntimeException('Select countries before choosing an audience.');
        }

        return DB::transaction(function () use ($campaign, $account, $match, $id, $operation, $expectedRevision, $countries): TargetingSet {
            $set = TargetingSet::query()->where('campaign_id', $campaign->getKey())->lockForUpdate()->first();

            if ($expectedRevision !== ($set?->revision ?? 0)) {
                throw new RuntimeException('Targeting changed since it was opened. Review the latest selection and try again.');
            }

            if ($set === null || $set->mode !== 'override') {
                $set = $this->locations->saveCampaignCountries($campaign, $countries, $expectedRevision);
                $set->refresh();
            }

            $selected = $this->selected($campaign);

            if (collect($selected)->contains(static fn (array $value): bool => $value['id'] === $id)) {
                throw new RuntimeException('This audience is already selected. Remove it before changing include or exclude.');
            }

            if (count($selected) >= 20) {
                throw new RuntimeException('Choose no more than 20 Meta audiences.');
            }

            $selected[] = [
                'id' => $id, 'name' => $match[0]['name'], 'subtype' => 'WEBSITE',
                'pixel_id' => $match[0]['pixel_id'], 'account_id' => $account, 'operation' => $operation,
            ];
            $set->update([
                'options' => [...(array) ($set->options ?? []), 'meta_audiences' => $selected],
                'revision' => $set->revision + 1,
            ]);
            $campaign->unsetRelation('targetingSet');

            return $set;
        });
    }

    public function recordCreated(Campaign $campaign, string $id, string $name, string $pixelId): TargetingSet
    {
        $account = $this->account($campaign);

        if ($campaign->isPublished() || (array) ($campaign->special_ad_categories ?? []) !== ['NONE']
            || ! preg_match('/^[0-9]+$/D', $id) || ! preg_match('/^[0-9]+$/D', $pixelId)
            || trim($name) === '') {
            throw new RuntimeException('A website audience can only be attached to an unrestricted draft Meta campaign.');
        }

        $countries = $this->locations->countries($campaign);

        if ($countries === []) {
            throw new RuntimeException('Select countries before attaching a website audience.');
        }

        $set = $campaign->targetingSet()->first();

        if ($set === null || $set->mode !== 'override') {
            $set = $this->locations->saveCampaignCountries($campaign, $countries);
        }

        $selected = $this->selected($campaign);

        if (collect($selected)->contains(static fn (array $audience): bool => $audience['id'] === $id)) {
            throw new RuntimeException('This website audience is already attached to the campaign.');
        }

        if (count($selected) >= 20) {
            throw new RuntimeException('Choose no more than 20 Meta audiences.');
        }

        // Graph has just created this id; normal save() requires an already-active listing.
        $selected[] = [
            'id' => $id,
            'name' => trim($name),
            'subtype' => 'WEBSITE',
            'pixel_id' => $pixelId,
            'account_id' => $account,
            'operation' => 'include',
        ];

        $set->update([
            'options' => [...(array) ($set->options ?? []), 'meta_audiences' => $selected],
            'revision' => $set->revision + 1,
        ]);
        $campaign->unsetRelation('targetingSet');

        return $set->fresh();
    }

    public function remove(Campaign $campaign, string $id, int $expectedRevision): TargetingSet
    {
        if ($campaign->platform !== 'meta' || $campaign->isPublished()) {
            throw new RuntimeException('Only a draft Meta campaign can remove an audience.');
        }

        return DB::transaction(function () use ($campaign, $id, $expectedRevision): TargetingSet {
            $set = TargetingSet::query()->where('campaign_id', $campaign->getKey())->lockForUpdate()->first()
                ?? throw new RuntimeException('This campaign has no audience to remove.');

            if ($set->revision !== $expectedRevision) {
                throw new RuntimeException('Targeting changed since it was opened. Review the latest selection and try again.');
            }

            $selected = $this->selected($campaign);
            $remaining = array_values(array_filter($selected, static fn (array $audience): bool => $audience['id'] !== $id));

            if (count($remaining) === count($selected)) {
                throw new RuntimeException('This audience is not selected on the campaign.');
            }

            $set->update([
                'options' => [...(array) ($set->options ?? []), 'meta_audiences' => $remaining],
                'revision' => $set->revision + 1,
            ]);
            $campaign->unsetRelation('targetingSet');

            return $set;
        });
    }

    private function account(Campaign $campaign): string
    {
        $account = $this->normaliseAccount((string) $campaign->ad_account_id);

        if ($campaign->platform !== 'meta' || ! preg_match('/^act_[0-9]+$/D', $account)) {
            throw new RuntimeException('Select a valid Meta ad account before choosing an audience.');
        }

        return $account;
    }

    private function normaliseAccount(string $account): string
    {
        $id = preg_replace('/^act_/', '', $account);

        return preg_match('/^[0-9]+$/D', (string) $id) ? 'act_'.$id : '';
    }

    /** @param  list<string>  $pixels */
    private function eligible(array $audience, string $account, array $pixels): bool
    {
        return preg_match('/^[0-9]+$/D', (string) ($audience['id'] ?? '')) === 1
            && trim((string) ($audience['name'] ?? '')) !== ''
            && $this->normaliseAccount((string) ($audience['account_id'] ?? '')) === $account
            && ($audience['subtype'] ?? null) === 'WEBSITE'
            && in_array((string) ($audience['pixel_id'] ?? ''), array_map('strval', $pixels), true)
            && (int) data_get($audience, 'operation_status.code') === 200
            && (int) data_get($audience, 'delivery_status.code') === 200;
    }
}
