<?php

namespace App\Campaigns\Targeting;

use App\Models\Campaign;
use App\Services\LinkedIn\LinkedInRestApi;
use App\Services\LinkedIn\LinkedInTargetingFacets;
use App\Services\Platforms\LinkedInAdapter;
use Throwable;

/**
 * LinkedIn's estimate for the audience a draft would publish, and the buyer's
 * confirmation to publish one below LinkedIn's minimum.
 *
 * The estimate is stored with a signature of the targeting it was taken for.
 * A changed audience makes it stale, and a stale or unavailable estimate never
 * blocks publishing: only a current estimate below the minimum asks for consent.
 */
class LinkedInAudienceSize
{
    public function __construct(
        private readonly TargetingSelections $targeting,
        private readonly LinkedInAudienceSelections $segments,
    ) {}

    /**
     * Ask LinkedIn for the current estimate and store it on the campaign.
     *
     * @return array{total: int, signature: string, checked_at: string}|null
     */
    public function refresh(Campaign $campaign): ?array
    {
        try {
            $signature = $this->signature($campaign);
            $size = [
                'total' => app(LinkedInRestApi::class)->audienceCount((string) $campaign->ad_account_id,
                    app(LinkedInAdapter::class)->audienceEstimateCriteria($campaign)),
                'signature' => $signature,
                'checked_at' => now()->toIso8601String(),
            ];
        } catch (Throwable) {
            return null;
        }

        $campaign->update(['meta' => [...(array) $campaign->meta, 'linkedin_audience_size' => $size]]);

        return $size;
    }

    /** @return array{total: int, signature: string, checked_at: string}|null */
    public function current(Campaign $campaign): ?array
    {
        $size = $campaign->meta['linkedin_audience_size'] ?? null;

        try {
            return is_array($size) && is_int($size['total'] ?? null) && ($size['signature'] ?? null) === $this->signature($campaign)
                ? $size
                : null;
        } catch (Throwable) {
            return null;
        }
    }

    public function isSmall(Campaign $campaign): bool
    {
        $size = $this->current($campaign);

        return $size !== null && $size['total'] < LinkedInTargetingFacets::SMALL_AUDIENCE_MINIMUM;
    }

    public function needsConfirmation(Campaign $campaign): bool
    {
        return $campaign->platform === 'linkedin'
            && $this->isSmall($campaign)
            && ($campaign->meta['linkedin_small_audience_confirmed'] ?? null) !== $this->current($campaign)['signature'];
    }

    public function confirm(Campaign $campaign): bool
    {
        $size = $this->current($campaign);
        if ($size === null || ! $this->isSmall($campaign)) {
            return false;
        }

        $campaign->update(['meta' => [...(array) $campaign->meta, 'linkedin_small_audience_confirmed' => $size['signature']]]);

        return true;
    }

    /** Readable estimate, e.g. "about 44,000 members" or "below 300 members". */
    public function describe(?array $size): ?string
    {
        if ($size === null) {
            return null;
        }

        return $size['total'] < LinkedInTargetingFacets::SMALL_AUDIENCE_MINIMUM
            ? 'below '.LinkedInTargetingFacets::SMALL_AUDIENCE_MINIMUM.' members, LinkedIn\'s minimum to deliver'
            : 'about '.number_format($size['total']).' members';
    }

    /** A fingerprint of every saved selection that changes who the campaign reaches. */
    public function signature(Campaign $campaign): string
    {
        $normalize = function (mixed $facets): array {
            $facets = (array) $facets;
            ksort($facets);

            return array_map(function (mixed $urns): array {
                $urns = array_values((array) $urns);
                sort($urns);

                return $urns;
            }, $facets);
        };
        $facets = $normalize($campaign->audience['linkedin_facets'] ?? []);
        $exclusions = $normalize($campaign->audience['linkedin_exclusions'] ?? []);
        $segments = array_map(fn (array $segment): string => $segment['operation'].'|'.$segment['urn'], $this->segments->selected($campaign));
        sort($segments);
        $countries = array_map(fn (mixed $code): string => strtoupper((string) $code), $this->targeting->countries($campaign));
        sort($countries);
        $markets = $this->targeting->linkedinDmaUrns($campaign);
        sort($markets);

        return sha1(json_encode([
            (string) $campaign->ad_account_id, $facets, array_values((array) ($campaign->audience['seniorities'] ?? [])),
            $segments, $countries, $markets, ...$exclusions === [] ? [] : [$exclusions],
        ]));
    }
}
