<?php

namespace App\Services\LinkedIn;

use App\Models\PlatformConnection;
use App\Services\Platforms\Support\CallContext;
use App\Services\Platforms\Support\CallLogger;
use App\Services\Platforms\Support\Guardrails;
use Carbon\CarbonImmutable;
use Illuminate\Http\Client\Response;
use Illuminate\Support\Facades\Http;

class LinkedInRestApi
{
    private const BASE_URL = 'https://api.linkedin.com';

    public function __construct(
        private readonly string $token,
        private readonly string $version,
        private readonly CallLogger $log,
    ) {}

    /**
     * List accessible ad accounts.
     *
     * @return list<array<string,mixed>>
     */
    /**
     * An id LinkedIn can actually parse, or a refusal that says so.
     *
     * Every id in this API is a number and every path is built from one. Nothing
     * checked, so a Meta-style act_ id, or an account name typed instead of an id,
     * went into the URL and LinkedIn answered "Failed to convert ... to
     * java.lang.Long" - a Java type error, in front of a media buyer, about a value
     * they could have fixed in a second if anything had said which value it was.
     *
     * Refused here as well as in the tool, because a path built from an unchecked
     * id is a class of bug rather than one call site, and eight of them in this file
     * had it.
     */
    private function numeric(string $id, string $what): string
    {
        return LinkedInUrn::numericId($id) ?? throw new LinkedInException(sprintf(
            '[%s] is not a LinkedIn %s id. LinkedIn ids are numbers, on their own or as a urn.',
            $id,
            $what,
        ));
    }

    public function adAccounts(): array
    {
        $response = $this->get('rest/adAccounts?q=search');

        return $response['elements'] ?? [];
    }

    /**
     * Get a specific ad account.
     */
    public function adAccount(string $adAccountId): array
    {
        return $this->get('rest/adAccounts/'.$this->numeric($adAccountId, 'ad account'));
    }

    public function lifetimeDelivery(string $adAccountId, string $type, string $id, int $createdAtMs): array
    {
        $account = $this->numeric($adAccountId, 'ad account');
        $created = $createdAtMs > 0 ? CarbonImmutable::createFromTimestampMs($createdAtMs, 'UTC') : null;
        if ($created === null || $created->isFuture() || $created->lt(now('UTC')->subYears(10)->startOfMonth())) {
            throw new LinkedInException('Complete lifetime delivery is unavailable: creation time is missing or outside reporting retention. Nothing was deleted.');
        }
        [$pivot, $filter, $urn] = match ($type) {
            'campaign' => ['CAMPAIGN', 'campaigns', LinkedInUrn::campaign($this->numeric($id, 'campaign'))],
            'campaign_group' => ['CAMPAIGN_GROUP', 'campaignGroups', LinkedInUrn::campaignGroup($this->numeric($id, 'campaign group'))],
            'creative', 'ad' => ['CREATIVE', 'creatives', LinkedInUrn::creative($this->numeric($id, 'creative'))],
            default => throw new LinkedInException('Choose campaign, campaign_group, creative, or ad for LinkedIn delivery review.'),
        };
        $start = sprintf('(year:%d,month:%d,day:%d)', $created->year, $created->month, $created->day);
        $endpoint = 'rest/adAnalytics?q=analytics&pivot='.$pivot.'&timeGranularity=ALL&dateRange=(start:'.$start.')'
            .'&accounts=List('.rawurlencode(LinkedInUrn::account($account)).')&'.$filter.'=List('.rawurlencode($urn).')'
            .'&fields=costInLocalCurrency,impressions,pivotValues';
        $rows = $this->get($endpoint, [], $account, memoize: false)['elements'] ?? null;
        // This is a completeness guard, not pagination: a response at the bound may be truncated.
        if (! is_array($rows) || $rows === [] || count($rows) >= 15000) {
            throw new LinkedInException('LinkedIn did not confirm lifetime delivery. Empty reports can also mean missing r_ads_reporting access; unknown spend is not zero.');
        }
        $spend = 0.0;
        $impressions = 0;
        foreach ($rows as $row) {
            if (($row['pivotValues'] ?? null) !== [$urn] || ! is_numeric($row['costInLocalCurrency'] ?? null)
                || ! is_numeric($row['impressions'] ?? null) || (float) $row['costInLocalCurrency'] < 0
                || (float) $row['impressions'] < 0 || (float) $row['impressions'] !== (float) (int) $row['impressions']) {
                throw new LinkedInException('LinkedIn returned incomplete or unrelated delivery metrics. Nothing was deleted.');
            }
            $spend += (float) $row['costInLocalCurrency'];
            $impressions += (int) $row['impressions'];
        }

        return ['spend' => $spend, 'impressions' => $impressions];
    }

    public function campaign(string $adAccountId, string $campaignId): array
    {
        return $this->accountEntity($adAccountId, 'adCampaigns', $this->numeric($campaignId, 'campaign'));
    }

    public function organizations(string $adAccountId): array
    {
        $account = $this->numeric($adAccountId, 'ad account');
        $organizations = [];
        for ($start = 0; $start < 1000; $start += 100) {
            $page = $this->get('rest/organizationAcls', ['q' => 'roleAssignee', 'state' => 'APPROVED', 'start' => $start, 'count' => 100], $account, memoize: false);
            foreach ($page['elements'] ?? [] as $role) {
                if (($role['state'] ?? null) !== 'APPROVED'
                    || ! in_array($role['role'] ?? null, ['ADMINISTRATOR', 'DIRECT_SPONSORED_CONTENT_POSTER', 'CONTENT_ADMINISTRATOR'], true)) {
                    continue;
                }
                $urn = $role['organization'] ?? $role['organizationTarget'] ?? '';
                $id = LinkedInUrn::numericId((string) $urn);
                if ($id !== null) {
                    $organizations[$id] = ['id' => (string) $id, 'urn' => $urn, 'name' => 'LinkedIn Page '.$id, 'role' => $role['role']];
                }
            }
            if (count($page['elements'] ?? []) < 100) {
                return $this->organizationNames($organizations, $account);
            }
        }

        throw new LinkedInException('Too many Page permissions to verify completely. Narrow the connected account before choosing a Page.');
    }

    private function organizationNames(array $organizations, string $account): array
    {
        foreach (array_chunk(array_keys($organizations), 100) as $ids) {
            try {
                $response = $this->get('rest/organizationsLookup?ids=List('.implode(',', $ids).')', [], $account, restliMethod: 'BATCH_GET');
            } catch (\Throwable) {
                $response = [];
            }
            foreach ($ids as $id) {
                $details = $response['results'][(string) $id] ?? null;
                if (is_array($details) && (string) ($details['id'] ?? '') === (string) $id && is_string($details['localizedName'] ?? null)) {
                    $organizations[$id]['name'] = $details['localizedName'];
                } else {
                    $organizations[$id]['name_unavailable'] = true;
                }
            }
        }

        return array_values($organizations);
    }

    public function campaignGroup(string $adAccountId, string $groupId): array
    {
        return $this->accountEntity($adAccountId, 'adCampaignGroups', $this->numeric($groupId, 'campaign group'));
    }

    public function video(string $adAccountId, string $videoUrn): array
    {
        if (! preg_match('/^urn:li:video:[A-Za-z0-9_-]+$/D', $videoUrn)) {
            throw new LinkedInException('Choose a valid LinkedIn video URN.');
        }

        return $this->get('rest/videos/'.rawurlencode($videoUrn), [], $this->numeric($adAccountId, 'ad account'), memoize: false);
    }

    public function uploadVideo(string $adAccountId, string $filePath, string $name, string $ownerUrn): string
    {
        $account = $this->numeric($adAccountId, 'ad account');
        $size = is_file($filePath) && is_readable($filePath) ? filesize($filePath) : false;
        if ($size === false || $size < 75000 || $size > 500 * 1024 * 1024 || ! preg_match('/^urn:li:organization:[0-9]+$/D', $ownerUrn)) {
            throw new LinkedInException('LinkedIn video needs a readable MP4 between 75 KB and 500 MB and a selected organization owner.');
        }
        $initialized = $this->post('rest/videos?action=initializeUpload', ['initializeUploadRequest' => [
            'owner' => $ownerUrn, 'fileSizeBytes' => $size, 'uploadCaptions' => false, 'uploadThumbnail' => false,
            'mediaLibraryMetadata' => ['associatedAccount' => LinkedInUrn::account($account), 'assetName' => $name],
        ]], $account)['value'] ?? [];
        $urn = (string) ($initialized['video'] ?? '');
        if (! preg_match('/^urn:li:video:[A-Za-z0-9_-]+$/D', $urn) || empty($initialized['uploadInstructions'])) {
            throw new LinkedInException('LinkedIn did not return a complete video upload session.');
        }
        $stream = fopen($filePath, 'rb');
        if ($stream === false) {
            throw new LinkedInException('The video file could not be opened.');
        }
        $partIds = [];
        $nextByte = 0;
        try {
            foreach ($initialized['uploadInstructions'] as $instruction) {
                $first = (int) ($instruction['firstByte'] ?? -1);
                $last = (int) ($instruction['lastByte'] ?? -1);
                $length = $last - $first + 1;
                $url = (string) ($instruction['uploadUrl'] ?? '');
                $host = strtolower((string) parse_url($url, PHP_URL_HOST));
                if ($first !== $nextByte || $last >= $size || $length <= 0 || $length > 4194304
                    || parse_url($url, PHP_URL_SCHEME) !== 'https'
                    || ! ($host === 'linkedin.com' || str_ends_with($host, '.linkedin.com') || str_ends_with($host, '.licdn.com'))) {
                    throw new LinkedInException('LinkedIn returned invalid video byte ranges or an untrusted upload URL.');
                }
                $bytes = stream_get_contents($stream, $length);
                if (! is_string($bytes) || strlen($bytes) !== $length) {
                    throw new LinkedInException('The video file was truncated during upload.');
                }
                $response = Http::timeout(120)->withoutRedirecting()->withBody($bytes, 'application/octet-stream')->put($url);
                $etag = trim((string) $response->header('ETag'), '"');
                if (! $response->successful() || $etag === '') {
                    throw new LinkedInException('A LinkedIn video part was not confirmed. Do not finalize or retry publication blindly.');
                }
                $partIds[] = $etag;
                $nextByte = $last + 1;
            }
        } finally {
            fclose($stream);
        }
        if ($nextByte !== $size) {
            throw new LinkedInException('LinkedIn upload instructions did not cover the complete video.');
        }
        $this->post('rest/videos?action=finalizeUpload', ['finalizeUploadRequest' => [
            'video' => $urn, 'uploadToken' => $initialized['uploadToken'] ?? '', 'uploadedPartIds' => $partIds,
        ]], $account);

        return $urn;
    }

    public function creative(string $adAccountId, string $creativeId): array
    {
        return $this->accountEntity($adAccountId, 'creatives', rawurlencode(LinkedInUrn::creative($this->numeric($creativeId, 'creative'))));
    }

    public function campaigns(string $adAccountId, ?string $pageToken = null, ?string $groupId = null): array
    {
        $search = $groupId === null
            ? '(status:(values:List(ACTIVE,PAUSED,ARCHIVED,COMPLETED,DRAFT)))'
            : '(campaignGroup:(values:List('.rawurlencode(LinkedInUrn::campaignGroup($this->numeric($groupId, 'campaign group'))).')))';

        return $this->entityPage($adAccountId, 'adCampaigns', ['q' => 'search', 'search' => $search], $pageToken);
    }

    public function campaignGroups(string $adAccountId, ?string $pageToken = null): array
    {
        return $this->entityPage($adAccountId, 'adCampaignGroups', [
            'q' => 'search', 'search' => '(status:(values:List(ACTIVE,PAUSED,ARCHIVED,DRAFT)))',
        ], $pageToken);
    }

    public function leadForms(string $adAccountId): array
    {
        $account = $this->numeric($adAccountId, 'ad account');
        $rows = $this->offsetEntities('rest/leadForms?q=owner&owner=(sponsoredAccount:'.rawurlencode(LinkedInUrn::account($account)).')', $account);

        return array_values(array_filter($rows, fn (array $form): bool => ($form['owner']['sponsoredAccount'] ?? null) === LinkedInUrn::account($account)
            && ($form['state'] ?? null) === 'PUBLISHED'
            && ($form['reviewInfo']['reviewStatus'] ?? null) !== 'REJECTED'));
    }

    public function professionalTargets(string $adAccountId, string $facet, ?string $query = null): array
    {
        $account = $this->numeric($adAccountId, 'ad account');
        $searchable = LinkedInTargetingFacets::searchable($facet);
        if (! LinkedInTargetingFacets::exists($facet)
            || ($searchable && (mb_strlen(trim((string) $query)) < 2 || mb_strlen((string) $query) > 100))) {
            throw new LinkedInException('Choose an allowed professional facet and search with 2 to 100 characters.');
        }
        $facetUrn = 'urn:li:adTargetingFacet:'.$facet;
        $response = $this->get('rest/adTargetingEntities', array_filter([
            'q' => $searchable ? 'typeahead' : 'adTargetingFacet', 'facet' => $facetUrn,
            'query' => $searchable ? trim((string) $query) : null,
            'queryVersion' => 'QUERY_USES_URNS',
        ], fn (mixed $value): bool => $value !== null), $account, memoize: false);

        return array_values(array_filter($response['elements'] ?? [], fn (array $entity): bool => ($entity['facetUrn'] ?? null) === $facetUrn && ($entity['isTargetable'] ?? true) === true
            && LinkedInTargetingFacets::accepts($facet, (string) ($entity['urn'] ?? ''))));
    }

    /**
     * Resolve saved targeting URNs, so publishing can confirm every one is still a
     * value of the facet it was saved under, whichever search found it.
     *
     * @param  list<string>  $urns
     * @return list<array{urn: string, facetUrn: string, name: string}>
     */
    public function targetingEntities(string $adAccountId, array $urns): array
    {
        $account = $this->numeric($adAccountId, 'ad account');
        $urns = array_values(array_unique($urns));
        if ($urns === [] || count($urns) > 500) {
            throw new LinkedInException('Choose between 1 and 500 saved targeting values to verify.');
        }
        $rows = [];
        foreach (array_chunk($urns, 50) as $chunk) {
            $response = $this->get('rest/adTargetingEntities?q=urns&queryVersion=QUERY_USES_URNS&urns=List('
                .implode(',', array_map('rawurlencode', $chunk)).')', [], $account, memoize: false);
            array_push($rows, ...($response['elements'] ?? []));
        }

        return $rows;
    }

    /**
     * LinkedIn's estimate of members matching complete targeting criteria.
     *
     * LinkedIn rounds the total and reports 0 below its minimum of 300 members.
     *
     * @param  array{include: array{and: list<array{or: array<string, list<string>>}>}, exclude?: array{or: array<string, list<string>>}}  $criteria
     */
    public function audienceCount(string $adAccountId, array $criteria): int
    {
        $account = $this->numeric($adAccountId, 'ad account');
        $facets = fn (array $or): string => implode(',', array_map(
            fn (string $facet, array $urns): string => rawurlencode($facet).':List('.implode(',', array_map('rawurlencode', $urns)).')',
            array_keys($or), $or,
        ));
        $encoded = '(include:(and:List('.implode(',', array_map(
            fn (array $clause): string => '(or:('.$facets((array) $clause['or']).'))',
            $criteria['include']['and'],
        )).'))'.(empty($criteria['exclude']['or']) ? '' : ',exclude:(or:('.$facets($criteria['exclude']['or']).'))').')';
        $total = data_get($this->get('rest/audienceCounts?q=targetingCriteriaV2&targetingCriteria='.$encoded, [], $account, memoize: false), 'elements.0.total');

        if (! is_numeric($total)) {
            throw new LinkedInException('LinkedIn did not return an audience estimate.');
        }

        return (int) $total;
    }

    public function conversions(string $adAccountId): array
    {
        $account = $this->numeric($adAccountId, 'ad account');
        $rows = $this->offsetEntities('rest/conversions?q=account&account='.rawurlencode(LinkedInUrn::account($account)), $account);

        return array_values(array_filter($rows, fn (array $conversion): bool => ($conversion['account'] ?? null) === LinkedInUrn::account($account) && ($conversion['enabled'] ?? false) === true));
    }

    private function offsetEntities(string $endpoint, string $account): array
    {
        $rows = [];
        for ($start = 0; $start < 1000; $start += 100) {
            $page = $this->get($endpoint.'&start='.$start.'&count=100', [], $account, memoize: false)['elements'] ?? [];
            array_push($rows, ...$page);
            if (count($page) < 100) {
                return $rows;
            }
        }

        throw new LinkedInException('Resource discovery exceeded 1000 entries. The result is incomplete; do not treat it as no eligible resources.');
    }

    public function insightTagHealth(string $adAccountId, string $landingUrl): array
    {
        $account = $this->numeric($adAccountId, 'ad account');
        $host = parse_url($landingUrl, PHP_URL_HOST);
        if (! is_string($host) || $host === '') {
            throw new LinkedInException('Choose a valid landing page before verifying the Insight Tag.');
        }
        $tags = $this->get('rest/insightTags', ['q' => 'account', 'account' => LinkedInUrn::account($account)], $account, memoize: false)['elements'] ?? [];
        $domains = $this->get('rest/insightTagDomains', ['q' => 'account', 'account' => LinkedInUrn::account($account),
            'count' => 100, 'start' => 0], $account, memoize: false)['elements'] ?? [];
        $domain = collect($domains)->first(fn (array $row): bool => strtolower((string) ($row['domainName'] ?? '')) === strtolower($host)
            && ($row['blocked'] ?? true) === false && (int) ($row['lastCallbackAt'] ?? 0) > 0);
        $tag = $domain === null ? null : collect($tags)->first(fn (array $row): bool => (string) ($domain['insightTag'] ?? '') === 'urn:tscp:insightTag:'.$row['id']
            && in_array(LinkedInUrn::account($account), $row['sponsoredAccounts'] ?? [], true));
        if ($tag === null) {
            throw new LinkedInException('No working Insight Tag is confirmed for this landing domain. Deploy the account tag on that website, visit it, and recheck after LinkedIn receives callbacks.');
        }

        return ['id' => (string) $tag['id'], 'domain' => $host, 'last_callback_at' => $domain['lastCallbackAt'], 'verified_at' => now()->toIso8601String()];
    }

    public function creatives(string $adAccountId, string $campaignId, ?string $pageToken = null): array
    {
        return $this->entityPage($adAccountId, 'creatives', [
            'q' => 'criteria', 'campaigns' => 'List('.rawurlencode(LinkedInUrn::campaign($this->numeric($campaignId, 'campaign'))).')',
        ], $pageToken);
    }

    public function associateConversion(string $adAccountId, string $campaignId, string $conversionId): void
    {
        $account = $this->numeric($adAccountId, 'ad account');
        $campaign = LinkedInUrn::campaign($this->numeric($campaignId, 'campaign'));
        $conversion = 'urn:lla:llaPartnerConversion:'.$this->numeric($conversionId, 'conversion');
        $endpoint = 'rest/campaignConversions/(campaign:'.rawurlencode($campaign).',conversion:'.rawurlencode($conversion).')';
        $payload = ['campaign' => $campaign, 'conversion' => $conversion];
        $this->log->record(new CallContext('linkedin_rest', 'PUT', $endpoint, $account, $payload, mutating: true, platform: 'linkedin'),
            fn (): array => $this->unwrap(Http::timeout(60)->withToken($this->token)->withHeaders($this->headers(true))->put($this->url($endpoint), $payload), $endpoint));
    }

    /** @return list<string> */
    public function campaignConversions(string $adAccountId, string $campaignId): array
    {
        $account = $this->numeric($adAccountId, 'ad account');
        $campaign = LinkedInUrn::campaign($this->numeric($campaignId, 'campaign'));
        $this->campaign($account, $campaignId);
        $conversions = [];
        for ($start = 0; $start < 1000; $start += 100) {
            $response = $this->get('rest/campaignConversions?q=campaigns&campaigns=List('.rawurlencode($campaign).')&start='.$start.'&count=100', [], $account, memoize: false);
            $rows = $response['elements'] ?? null;
            if (! is_array($rows) || ! array_is_list($rows)) {
                throw new LinkedInException('LinkedIn did not return complete campaign conversion associations.');
            }
            foreach ($rows as $row) {
                if (! is_array($row) || ($row['campaign'] ?? null) !== $campaign
                    || ! is_string($row['conversion'] ?? null)
                    || ! preg_match('/^urn:lla:llaPartnerConversion:[0-9]+$/D', $row['conversion'])) {
                    throw new LinkedInException('LinkedIn returned an incomplete or unrelated conversion association.');
                }
                $conversions[] = $row['conversion'];
            }
            if (count($rows) < 100) {
                $conversions = array_values(array_unique($conversions));
                sort($conversions);

                return $conversions;
            }
        }

        throw new LinkedInException('Campaign conversion associations exceeded the complete-read limit.');
    }

    /** @param list<string> $desired */
    public function replaceCampaignConversions(string $adAccountId, string $campaignId, array $desired, ?array $expected = null): void
    {
        if (! array_is_list($desired) || count($desired) > 100
            || array_filter($desired, fn (mixed $value): bool => ! is_string($value) || ! preg_match('/^urn:lla:llaPartnerConversion:[0-9]+$/D', $value)) !== []
            || count(array_unique($desired)) !== count($desired)) {
            throw new LinkedInException('Choose distinct LinkedIn conversion rule URNs.');
        }
        $current = $this->campaignConversions($adAccountId, $campaignId);
        if ($expected !== null) {
            sort($expected);
            if ($current !== $expected) {
                throw new LinkedInException('Conversion associations changed after review. Refresh before trying again; nothing was sent.');
            }
        }
        $eligible = array_map(fn (array $row): string => 'urn:lla:llaPartnerConversion:'.$this->numeric((string) $row['id'], 'conversion'), $this->conversions($adAccountId));
        if (array_diff($desired, [...$current, ...$eligible]) !== []) {
            throw new LinkedInException('Choose distinct enabled conversion rules belonging to this LinkedIn account.');
        }
        foreach (array_diff($desired, $current) as $conversion) {
            $this->associateConversion($adAccountId, $campaignId, $conversion);
        }
        foreach (array_diff($current, $desired) as $conversion) {
            $campaign = LinkedInUrn::campaign($this->numeric($campaignId, 'campaign'));
            $this->deleteCall('rest/campaignConversions/(campaign:'.rawurlencode($campaign).',conversion:'.rawurlencode($conversion).')', $adAccountId);
        }
    }

    private function accountEntity(string $adAccountId, string $resource, string $key): array
    {
        $account = $this->numeric($adAccountId, 'ad account');
        $entity = $this->get("rest/adAccounts/{$account}/{$resource}/{$key}", [], $account, memoize: false);
        $this->assertEntityAccount($entity, $account);

        return $entity;
    }

    private function assertEntityAccount(array $entity, string $account): void
    {
        if (($entity['account'] ?? null) !== LinkedInUrn::account($account)) {
            throw new LinkedInException('LinkedIn did not confirm this entity belongs to the requested ad account.');
        }
    }

    private function entityPage(string $adAccountId, string $resource, array $query, ?string $pageToken): array
    {
        $account = $this->numeric($adAccountId, 'ad account');
        if ($pageToken !== null && (strlen($pageToken) > 2048 || preg_match('/[\x00-\x1F]/', $pageToken))) {
            throw new LinkedInException('Invalid LinkedIn pagination token.');
        }

        $parameters = array_filter([
            ...$query, 'pageSize' => 50, 'pageToken' => $pageToken,
        ], fn (mixed $value): bool => $value !== null);
        $encoded = [];
        foreach ($parameters as $key => $value) {
            $encoded[] = rawurlencode($key).'='.(in_array($key, ['search', 'campaigns'], true) ? $value : rawurlencode((string) $value));
        }
        $response = $this->get("rest/adAccounts/{$account}/{$resource}?".implode('&', $encoded), [], $account, memoize: false);
        $elements = (array) ($response['elements'] ?? []);
        foreach ($elements as $entity) {
            $this->assertEntityAccount($entity, $account);
        }

        return ['elements' => $elements, 'next_page_token' => $response['metadata']['nextPageToken'] ?? null];
    }

    /** @return list<array<string, mixed>> */
    public function adSegments(string $adAccountId): array
    {
        $accountUrn = LinkedInUrn::account($adAccountId);
        $segments = [];

        for ($start = 0; $start < 500; $start += 100) {
            $endpoint = 'rest/adSegments?q=accounts&accounts=List('.rawurlencode($accountUrn)
                .')&start='.$start.'&count=100';
            $response = $this->get($endpoint, [], $adAccountId);
            $page = (array) ($response['elements'] ?? []);
            array_push($segments, ...$page);

            if (count($page) < 100) {
                break;
            }
        }

        return $segments;
    }

    /** @return array<string, mixed> */
    public function adSegment(string $adAccountId, string $segmentId): array
    {
        return $this->get('rest/adSegments/'.$this->numeric($segmentId, 'ad segment'), [], $adAccountId);
    }

    /** @return list<array<string, mixed>> */
    public function countryCandidates(string $countryName, ?string $adAccountId = null): array
    {
        $response = $this->get('rest/adTargetingEntities', [
            'q' => 'typeahead',
            'facet' => 'urn:li:adTargetingFacet:locations',
            'queryVersion' => 'QUERY_USES_URNS',
            'query' => $countryName,
        ], $adAccountId);

        return (array) ($response['elements'] ?? []);
    }

    /**
     * Places LinkedIn can target for a search such as "new york".
     *
     * The same typeahead Campaign Manager uses. A state, city, metro, and
     * county are all geo URNs. Anything that is not a targetable geo URN is
     * left out.
     *
     * @return list<array{urn: string, name: string}>
     */
    public function locationCandidates(string $adAccountId, string $query): array
    {
        $query = trim($query);

        if (mb_strlen($query) < 2 || mb_strlen($query) > 80) {
            throw new LinkedInException('Search LinkedIn locations with 2 to 80 characters.');
        }

        $places = [];

        foreach ($this->countryCandidates($query, $adAccountId) as $candidate) {
            $urn = (string) ($candidate['urn'] ?? '');
            $name = trim((string) ($candidate['name'] ?? ''));

            if ($name === '' || ! preg_match('/^urn:li:geo:[0-9]+$/D', $urn)) {
                continue;
            }

            if (isset($candidate['facetUrn']) && $candidate['facetUrn'] !== 'urn:li:adTargetingFacet:locations') {
                continue;
            }

            if (($candidate['isTargetable'] ?? true) !== true) {
                continue;
            }

            $places[$urn] = ['urn' => $urn, 'name' => $name];
        }

        return array_values($places);
    }

    /**
     * Resolve a DMA geo URN as a targeting criterion without creating a campaign.
     * Rest.li requires the expression punctuation to stay literal and only URNs
     * to be URL encoded; passing the expression as an ordinary query parameter
     * makes LinkedIn reject it as malformed.
     */
    public function dmaAudienceCount(string $geoUrn, string $adAccountId): int
    {
        if (! preg_match('/^urn:li:geo:[0-9]+$/D', $geoUrn)) {
            throw new LinkedInException('Choose an exact LinkedIn DMA geo URN.');
        }

        $criteria = '(include:(and:List((or:('.rawurlencode('urn:li:adTargetingFacet:locations')
            .':List('.rawurlencode($geoUrn).'))))))';
        $response = $this->get('rest/audienceCounts?q=targetingCriteriaV2&targetingCriteria='.$criteria, [], $adAccountId);
        $total = data_get($response, 'elements.0.total');

        if (! is_numeric($total) || (int) $total <= 0) {
            throw new LinkedInException('LinkedIn did not confirm an eligible audience for this DMA market.');
        }

        return (int) $total;
    }

    /**
     * Create a campaign group (container for campaigns).
     *
     * @param  array<string,mixed>  $payload
     * @return array<string,mixed>
     */
    public function createCampaignGroup(string $adAccountId, array $payload): array
    {
        $bareId = $this->numeric($adAccountId, 'ad account');
        $accountUrn = LinkedInUrn::account($adAccountId);

        $body = [
            'account' => $accountUrn,
            'name' => $payload['name'],
            // DRAFT, not PAUSED, and not because PAUSED is unsafe.
            //
            // This defaulted to ACTIVE and skipped the guard entirely, so the
            // one object that decides whether everything beneath it can deliver
            // was the one object the kill switch never saw. Setting PAUSED
            // fixed that and broke creation outright: LinkedIn refuses the
            // transition with "/CampaignGroup/status cannot be changed from
            // null to PAUSED", because a group is created DRAFT or ACTIVE and
            // only moves to PAUSED afterwards. Every LinkedIn publish failed
            // on it, which no Http::fake could show.
            //
            // DRAFT is the stricter of the two anyway: a paused group can be
            // resumed, a draft one has never been live at all.
            'status' => 'DRAFT',
            'runSchedule' => [
                'start' => (int) (now()->timestamp * 1000),
            ],
            ...$payload,
        ];

        return $this->post("rest/adAccounts/{$bareId}/adCampaignGroups", $body, $adAccountId);
    }

    /**
     * Create a campaign (holds targeting, schedule, budget, and objective).
     *
     * @param  array<string,mixed>  $payload
     * @return array<string,mixed>
     */
    public function createCampaign(string $adAccountId, array $payload): array
    {
        $bareId = $this->numeric($adAccountId, 'ad account');
        $accountUrn = LinkedInUrn::account($adAccountId);

        $body = [
            'account' => $accountUrn,
            'name' => $payload['name'],
            'status' => 'PAUSED',
            'runSchedule' => [
                'start' => (int) (now()->timestamp * 1000),
            ],
            'locale' => [
                'country' => 'US',
                'language' => 'en',
            ],
            'offsiteDeliveryEnabled' => false,
            'politicalIntent' => 'NOT_POLITICAL',
            ...$payload,
        ];

        return $this->post("rest/adAccounts/{$bareId}/adCampaigns", $body, $adAccountId);
    }

    /**
     * Upload an image to LinkedIn and return the image URN (e.g. urn:li:image:xxx).
     */
    public function uploadImage(string $adAccountId, string $filePath, ?string $name = null, ?string $ownerUrn = null): string
    {
        $orgId = PlatformConnection::sharedMetadata('linkedin', 'organization_id', config('platforms.linkedin.organization_id'));
        $owner = $ownerUrn
            ?? ($orgId ? LinkedInUrn::organization((string) $orgId) : LinkedInUrn::account($adAccountId));

        $initializeUploadRequest = [
            'owner' => $owner,
        ];

        if (str_starts_with($owner, 'urn:li:organization:') && ! empty($adAccountId)) {
            $initializeUploadRequest['mediaLibraryMetadata'] = [
                'associatedAccount' => LinkedInUrn::account($adAccountId),
            ];
            if (! empty($name)) {
                $initializeUploadRequest['mediaLibraryMetadata']['assetName'] = $name;
            }
        }

        $initResponse = $this->post('rest/images?action=initializeUpload', [
            'initializeUploadRequest' => $initializeUploadRequest,
        ], $adAccountId);

        $uploadUrl = $initResponse['value']['uploadUrl'] ?? null;
        $imageUrn = $initResponse['value']['image'] ?? null;

        if (! $uploadUrl || ! $imageUrn) {
            throw new LinkedInException('Failed to initialize image upload on LinkedIn.');
        }

        // Checked before reading. file_get_contents() on a missing path warns
        // and returns false, and Http::withBody(false) uploads an empty body,
        // so LinkedIn was handed a zero byte image and the ad was built around
        // it. The same guard is on GraphApi::multipart() for the same reason.
        if (! is_file($filePath)) {
            throw new LinkedInException(sprintf(
                'The file for %s is missing, so it could not be uploaded to LinkedIn.',
                $name ?: basename($filePath),
            ));
        }

        $binary = file_get_contents($filePath);
        $mime = mime_content_type($filePath) ?: 'application/octet-stream';
        $put = Http::withBody($binary, $mime)->put($uploadUrl);

        if (! $put->successful()) {
            throw new LinkedInException("Failed to upload image binary to LinkedIn: {$put->status()} {$put->body()}");
        }

        return $imageUrn;
    }

    /**
     * Create a sponsored creative / ad.
     *
     * @param  array<string,mixed>  $payload
     * @return array<string,mixed>
     */
    public function createCreative(string $adAccountId, array $payload): array
    {
        $bareId = $this->numeric($adAccountId, 'ad account');

        // The caller's own value, and DRAFT when it has not said.
        //
        // This forced ACTIVE over whatever it was given, and relied on the removed
        // ensureSafeStatus() to pull it back down - so the adapter's intent was
        // overwritten twice on the way out, once in each direction. Every creative
        // this product builds is a draft until an approved activation says
        // otherwise, so that is the default; overriding the caller is not this
        // layer's job either way.
        $body = [
            'intendedStatus' => 'DRAFT',
            ...$payload,
        ];

        unset($body['status']);

        return $this->post("rest/adAccounts/{$bareId}/creatives", $body, $adAccountId);
    }

    /**
     * Create a post or Direct Sponsored Content (dark post).
     *
     * @param  array<string,mixed>  $payload
     * @return array<string,mixed>
     */
    public function createPost(array $payload, ?string $adAccountId = null): array
    {
        return $this->post('rest/posts', $payload, $adAccountId);
    }

    /**
     * A post as its author sees it, which is the only view that returns a draft.
     *
     * @return array<string,mixed>
     */
    public function authoredPost(string $adAccountId, string $postUrn): array
    {
        return $this->get('rest/posts/'.rawurlencode($postUrn), ['viewContext' => 'AUTHOR'], $this->numeric($adAccountId, 'ad account'), memoize: false);
    }

    /**
     * Update an entity (campaign, campaign group, or creative).
     *
     * @param  array<string,mixed>  $patchFields
     * @param  list<string>  $deleteFields
     * @return array<string,mixed>
     */
    public function updateEntity(string $adAccountId, string $entityType, string $entityId, array $patchFields, array $deleteFields = []): array
    {
        $bareAccountId = $this->numeric($adAccountId, 'ad account');
        $id = $this->numeric($entityId, 'entity');

        $creativeKey = urlencode(LinkedInUrn::creative($id));
        $endpoint = match ($entityType) {
            'campaign_group' => "rest/adAccounts/{$bareAccountId}/adCampaignGroups/{$id}",
            'campaign' => "rest/adAccounts/{$bareAccountId}/adCampaigns/{$id}",
            'creative' => "rest/adAccounts/{$bareAccountId}/creatives/{$creativeKey}",
            default => "rest/adAccounts/{$bareAccountId}/{$entityType}/{$id}",
        };

        $patch = $patchFields === [] ? [] : ['$set' => $patchFields];
        if ($deleteFields !== []) {
            $patch['$delete'] = $deleteFields;
        }

        return $this->post($endpoint, ['patch' => $patch], $adAccountId);
    }

    /*
     * Nothing here rewrites what a caller asked for.
     *
     * There was a guard that quietly turned ACTIVE into PAUSED and PUBLISHED into
     * DRAFT on the way out, and updateEntity did the same for status. It was doing
     * a real job badly: the adapter above asked for ACTIVE, believed it had got it,
     * and something invisible disagreed. While that rewrite did not yet cover
     * lifecycleState, a real sponsored post went out publicly with the campaign
     * over it correctly paused - exactly the failure a silent correction invites,
     * because nobody can see which cases it is not covering.
     *
     * The adapter builds draft now, because that is what building means, and going
     * live is an approved decision with a tool behind it. A guard that refuses is a
     * guard; one that edits your payload and says nothing is a second author.
     */

    /**
     * Delete or cancel an entity.
     */
    public function delete(string $adAccountId, string $entityType, string $entityId): bool
    {
        $bareAccountId = $this->numeric($adAccountId, 'ad account');
        $id = $this->numeric($entityId, 'entity');
        $creativeKey = urlencode(LinkedInUrn::creative($id));
        $endpoint = match ($entityType) {
            'campaign_group' => "rest/adAccounts/{$bareAccountId}/adCampaignGroups/{$id}",
            'campaign' => "rest/adAccounts/{$bareAccountId}/adCampaigns/{$id}",
            'creative' => "rest/adAccounts/{$bareAccountId}/creatives/{$creativeKey}",
            default => "rest/adAccounts/{$bareAccountId}/{$entityType}/{$id}",
        };

        $result = $this->deleteCall($endpoint, $adAccountId);

        return ($result['status'] ?? 200) < 300;
    }

    // ------------------------------------------------------------- internals

    private function get(string $endpoint, array $query = [], ?string $adAccountId = null, bool $memoize = true, ?string $restliMethod = null): array
    {
        return $this->log->record(
            new CallContext('linkedin_rest', 'GET', $endpoint, $adAccountId, $query, mutating: false, platform: 'linkedin', memoize: $memoize),
            fn (): array => $this->unwrap(
                Http::timeout(60)
                    ->withToken($this->token)
                    ->withHeaders($this->headers(hasBody: false))
                    ->withHeaders(isset($query['q']) || str_contains($endpoint, '?q=') ? ['X-RestLi-Method' => 'FINDER'] : [])
                    ->withHeaders($restliMethod !== null ? ['X-RestLi-Method' => $restliMethod] : [])
                    ->get($this->url($endpoint), ! empty($query) ? $query : null),
                $endpoint,
            ),
        );
    }

    private function post(string $endpoint, array $data, ?string $adAccountId = null): array
    {
        return $this->log->record(
            new CallContext('linkedin_rest', 'POST', $endpoint, $adAccountId, $data, mutating: true, platform: 'linkedin'),
            fn (): array => $this->unwrap(
                Http::timeout(120)
                    ->withToken($this->token)
                    ->withHeaders($this->headers(hasBody: true))
                    ->withHeaders(isset($data['patch']) ? ['X-RestLi-Method' => 'PARTIAL_UPDATE'] : [])
                    ->post($this->url($endpoint), $data),
                $endpoint,
            ),
        );
    }

    private function deleteCall(string $endpoint, ?string $adAccountId = null): array
    {
        return $this->log->record(
            new CallContext('linkedin_rest', 'DELETE', $endpoint, $adAccountId, [], mutating: true, platform: 'linkedin'),
            fn (): array => $this->unwrap(
                Http::timeout(60)
                    ->withToken($this->token)
                    ->withHeaders($this->headers(hasBody: false))
                    ->withHeaders(['X-RestLi-Method' => 'DELETE'])
                    ->delete($this->url($endpoint)),
                $endpoint,
            ),
        );
    }

    private function unwrap(Response $response, string $endpoint): array
    {
        if ($response->status() === 204) {
            return ['status' => 204];
        }

        // LinkedIn 201 Created returns entity ID in x-restli-id header
        if ($response->status() === 201) {
            $createdId = $response->header('x-restli-id') ?? $response->header('x-linkedin-id');
            $body = $response->json();

            if (is_array($body)) {
                return ['id' => $createdId, ...$body];
            }

            return ['id' => $createdId];
        }

        $body = $response->json();

        if (! is_array($body)) {
            if ($response->successful()) {
                return ['status' => $response->status()];
            }

            throw new LinkedInException(sprintf('HTTP %d response from LinkedIn on %s', $response->status(), $endpoint));
        }

        // The HTTP status decides, not the presence of a word.
        //
        // This also threw whenever the body carried a `message` key, and
        // `message` is ordinary content on LinkedIn: a post has one, and so
        // does an InMail creative. A successful 201 from rest/posts was being
        // turned into an exception because the thing we had just created
        // contained the text we asked it to contain.
        //
        // An `error` key on a successful response is still worth trusting,
        // because LinkedIn does occasionally answer 200 with one.
        if ($response->failed() || isset($body['error'])) {
            $message = $body['message'] ?? $body['error']['message'] ?? $body['error'] ?? 'Unknown LinkedIn error';
            $code = $body['code'] ?? $body['status'] ?? $response->status();
            $safeBody = app(Guardrails::class)->scrubCredentials($body);
            $details = $safeBody['errorDetails'] ?? $safeBody['error']['errorDetails'] ?? null;
            $detailsMessage = $details === null ? '' : ' Validation details: '.json_encode($details, JSON_UNESCAPED_SLASHES);

            throw new LinkedInException(sprintf(
                '%s [LinkedIn %s] on %s%s',
                is_string($message) ? $message : json_encode($message),
                is_scalar($code) ? $code : $response->status(),
                $endpoint,
                $detailsMessage,
            ), diagnostics: ['http_status' => $response->status(), 'response' => $safeBody]);
        }

        return $body;
    }

    private function url(string $endpoint): string
    {
        return self::BASE_URL.'/'.ltrim($endpoint, '/');
    }

    /**
     * @return array<string, string>
     */
    private function headers(bool $hasBody = false): array
    {
        $headers = [
            'LinkedIn-Version' => $this->version,
            'X-Restli-Protocol-Version' => '2.0.0',
            'Accept' => 'application/json',
        ];

        if ($hasBody) {
            $headers['Content-Type'] = 'application/json';
        }

        return $headers;
    }
}
