<?php

namespace App\Services\Meta;

use App\Campaigns\MetaPromotedConversion;
use App\Campaigns\Objectives;

/**
 * Everything an ad set needs, in one place, so the two transports build the
 * same request from the same source rather than drifting apart.
 */
readonly class AdSetSpec
{
    /**
     * @param  int  $budgetMinorUnits  ignored when the campaign holds the budget
     * @param  string  $budgetLevel  'adset' or 'campaign'
     * @param  string  $budgetMode  'daily' or 'lifetime'
     */
    public function __construct(
        public string $adAccountId,
        public string $campaignId,
        public string $name,
        public int $budgetMinorUnits,
        public string $optimizationGoal,
        public array $targeting,
        public string $pageId,
        public ?string $pixelId = null,
        public ?string $conversionEvent = null,
        public string $bidStrategy = 'LOWEST_COST_WITHOUT_CAP',
        public ?int $bidAmountCents = null,
        public ?\DateTimeInterface $startsAt = null,
        public ?\DateTimeInterface $endsAt = null,
        public string $budgetLevel = 'adset',
        public string $budgetMode = 'daily',
        // Carried so the audit line can render the amount as money. The number
        // above is in the currency's minor units and the yen has none, so
        // dividing by 100 to print it reported a hundredth of the truth.
        public ?string $currency = null,
        public ?string $dsaBeneficiary = null,
        public ?string $dsaPayor = null,
        public ?string $universalBeneficiary = null,
        public ?string $universalPayer = null,
        public array $regionalRegulatedCategories = [],
    ) {}

    /**
     * The verified advertiser, required when the ad account demands one.
     *
     * @return array<string, string>
     */
    public function advertiserFields(): array
    {
        $identities = null;

        if (is_string($this->universalBeneficiary) && $this->universalBeneficiary !== '') {
            $payer = is_string($this->universalPayer) && $this->universalPayer !== ''
                ? $this->universalPayer
                : $this->universalBeneficiary;
            $identities = json_encode([
                'universal_beneficiary' => $this->universalBeneficiary,
                'universal_payer' => $payer,
            ]);
        }

        $categories = array_values(array_unique(array_filter(
            $this->regionalRegulatedCategories,
            fn (mixed $category): bool => is_string($category) && $category !== '',
        )));

        return array_filter([
            'dsa_beneficiary' => $this->dsaBeneficiary,
            'dsa_payor' => $this->dsaPayor,
            'regional_regulated_categories' => $categories === [] ? null : json_encode($categories),
            'regional_regulation_identities' => $identities,
        ], fn (mixed $value): bool => is_string($value) && $value !== '');
    }

    /**
     * Budget and bidding, which move together.
     *
     * Under Advantage campaign budget the money and the strategy both sit on
     * the campaign, and repeating either here is rejected rather than ignored.
     * The cost cap amount stays on the ad set in both arrangements, because it
     * is a per-ad-set target even when Meta is deciding the split.
     *
     * @return array<string, mixed>
     */
    public function budgetFields(): array
    {
        if ($this->budgetLevel === 'campaign') {
            return array_filter(['bid_amount' => $this->bidAmountCents]);
        }

        return array_filter([
            $this->budgetMode === 'lifetime' ? 'lifetime_budget' : 'daily_budget' => $this->budgetMinorUnits,
            'bid_strategy' => $this->bidStrategy,
            'bid_amount' => $this->bidAmountCents,
        ], fn (mixed $value): bool => $value !== null);
    }

    /**
     * When the ad set runs.
     *
     * ISO 8601 with an offset, deliberately. Meta reads a bare local-format
     * string in the ad account's own timezone, which is frequently not ours, so
     * an unqualified string quietly shifts the start by hours.
     *
     * @return array<string, string>
     */
    public function schedule(): array
    {
        return array_filter([
            'start_time' => $this->startsAt?->format(\DateTimeInterface::ATOM),
            'end_time' => $this->endsAt?->format(\DateTimeInterface::ATOM),
        ]);
    }

    /**
     * Meta's targeting spec.
     *
     * Naming a publisher platform switches off automatic placement, so the
     * positions within each platform have to be named too or the ad set is
     * rejected.
     */
    public function targetingSpec(): array
    {
        $spec = [
            'geo_locations' => $this->targeting['geo_locations'] ?? ['countries' => array_values($this->targeting['countries'])],
            'age_min' => $this->targeting['age_min'] ?? 18,
            'age_max' => $this->targeting['age_max'] ?? 65,
            'targeting_automation' => ['advantage_audience' => 0],
        ];

        if (! empty($this->targeting['genders'])) {
            $spec['genders'] = array_values($this->targeting['genders']);   // 1 male, 2 female
        }

        $detailed = $this->flexibleTargeting();

        if ($detailed === [] && ! empty($this->targeting['meta_interests'])) {
            $spec['interests'] = $this->interestObjects($this->targeting['meta_interests']);
        }

        if ($detailed !== []) {
            $spec['flexible_spec'] = $detailed;
        }

        foreach (['user_os', 'user_device'] as $deviceField) {
            $devices = $this->deviceNames($this->targeting['meta_detailed'][$deviceField] ?? []);

            if ($devices !== []) {
                $spec[$deviceField] = $devices;
            }
        }

        if (! empty($this->targeting['meta_custom_audiences'])) {
            $spec['custom_audiences'] = $this->targeting['meta_custom_audiences'];
        }

        if (! empty($this->targeting['meta_excluded_custom_audiences'])) {
            $spec['excluded_custom_audiences'] = $this->targeting['meta_excluded_custom_audiences'];
        }

        if (! empty($this->targeting['devices'])) {
            $spec['device_platforms'] = array_values($this->targeting['devices']);
        }

        if (! empty($this->targeting['placements'])) {
            $requestedPlacements = array_values(array_unique($this->targeting['placements']));
            $threadsRequiresInstagramFeed = in_array('threads', $requestedPlacements, true)
                && ! in_array('instagram', $requestedPlacements, true);
            $placements = $requestedPlacements;

            if ($threadsRequiresInstagramFeed) {
                $placements[] = 'instagram';
            }

            $spec['publisher_platforms'] = $placements;

            foreach ($placements as $platform) {
                if ($positions = self::POSITIONS[$platform] ?? null) {
                    if ($platform === 'instagram' && $threadsRequiresInstagramFeed) {
                        $positions = ['stream'];
                    }

                    $spec[$platform === 'audience_network' ? 'audience_network_positions' : "{$platform}_positions"] = $positions;
                }
            }
        }

        return $spec;
    }

    /**
     * One flexible_spec group per targeting type.
     *
     * Meta ORs the values inside a group and ANDs the groups, which is the
     * same combination as a LinkedIn facet: any selected job title, and the
     * selected education level. Interest-only audiences stay on the top-level
     * interests field so an older campaign publishes as it did before.
     *
     * @return list<array<string, mixed>>
     */
    private function flexibleTargeting(): array
    {
        $detailed = is_array($this->targeting['meta_detailed'] ?? null) ? $this->targeting['meta_detailed'] : [];
        $groups = [];

        foreach (self::FLEXIBLE_FIELDS as $field) {
            $values = $detailed[$field] ?? [];

            if (! is_array($values) || $values === []) {
                continue;
            }

            if (in_array($field, ['education_statuses', 'relationship_statuses'], true)) {
                $ids = array_values(array_unique(array_map(
                    static fn (array $item): int => (int) $item['id'],
                    array_filter($values, 'is_array'),
                )));

                if ($ids !== []) {
                    $groups[] = [$field => $ids];
                }

                continue;
            }

            $objects = $this->interestObjects($values);

            if ($objects !== []) {
                $groups[] = [$field => $objects];
            }
        }

        if ($groups !== [] && ! empty($this->targeting['meta_interests'])) {
            $already = collect($groups)->contains(fn (array $group): bool => isset($group['interests']));

            if (! $already) {
                $objects = $this->interestObjects($this->targeting['meta_interests']);

                if ($objects !== []) {
                    array_unshift($groups, ['interests' => $objects]);
                }
            }
        }

        return $groups;
    }

    /**
     * @param  list<mixed>  $items
     * @return list<array{id: string, name?: string}>
     */
    private function interestObjects(array $items): array
    {
        return array_values(array_filter(array_map(
            static function (mixed $item): ?array {
                if (! is_array($item) || ! preg_match('/^[0-9]+$/D', (string) ($item['id'] ?? ''))) {
                    return null;
                }

                return array_filter([
                    'id' => (string) $item['id'],
                    'name' => (string) ($item['name'] ?? ''),
                ], static fn (string $value): bool => $value !== '');
            },
            $items,
        )));
    }

    /**
     * @return list<string>
     */
    private function deviceNames(mixed $items): array
    {
        if (! is_array($items)) {
            return [];
        }

        return array_values(array_unique(array_filter(array_map(
            static fn (mixed $item): string => is_array($item) ? trim((string) ($item['name'] ?? '')) : '',
            $items,
        ))));
    }

    /**
     * What the ad set optimises toward: a pixel event, the Page, or nothing.
     *
     * Nothing is a real answer for reach, where there is no object being
     * optimised toward, only people being counted, and Meta rejects a promoted
     * object sent against it.
     */
    public function promotedObject(): array
    {
        if ($this->pixelId && $this->conversionEvent) {
            return MetaPromotedConversion::promotedObject($this->pixelId, $this->conversionEvent);
        }

        // A Page, or nothing. Never a catalogue: product_catalog_id and
        // product_set_id are what turn on Advantage+ catalogue.
        return Objectives::needsPromotedObject($this->optimizationGoal)
            ? ['page_id' => $this->pageId]
            : [];
    }

    /** @var list<string> */
    private const FLEXIBLE_FIELDS = [
        'interests',
        'behaviors',
        'life_events',
        'income',
        'family_statuses',
        'industries',
        'education_statuses',
        'education_majors',
        'education_schools',
        'work_employers',
        'work_positions',
        'relationship_statuses',
    ];

    /**
     * The positions named within each platform.
     *
     * facebook no longer lists video_feeds, and instagram no longer lists
     * explore. Meta retired both and refuses the whole ad set rather than
     * ignoring them: "placement is deprecated for this API version and cannot
     * be selected". Since naming any publisher platform switches off automatic
     * placement and forces these lists to be sent, one retired position is
     * enough to make every campaign choosing that platform fail at the ad set.
     *
     * Meta retires positions without notice, so anything added here should be
     * confirmed against a real ad set create rather than against the docs.
     */
    private const POSITIONS = [
        'facebook' => ['feed', 'story', 'facebook_reels', 'marketplace', 'search'],
        'instagram' => ['stream', 'story', 'reels'],
        'messenger' => ['messenger_home', 'story'],
        'audience_network' => ['classic', 'rewarded_video'],
        'threads' => ['threads_stream'],
    ];
}
