<?php

namespace App\Campaigns\Targeting;

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

class LinkedInAudienceSelections
{
    public function __construct(
        private readonly LinkedIn $linkedin,
        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.');
        }

        return collect($this->linkedin->adSegments($account))
            ->filter(static fn (array $segment): bool => $query === null
                || str_contains(mb_strtolower((string) ($segment['name'] ?? '')), mb_strtolower(trim($query))))
            ->map(fn (array $segment): array => [
                'urn' => 'urn:li:adSegment:'.($segment['id'] ?? ''),
                'name' => (string) ($segment['name'] ?? ''),
                'type' => (string) ($segment['type'] ?? ''),
                'status' => (string) ($segment['status'] ?? ''),
                'account' => (string) ($segment['account'] ?? ''),
                'approximate_member_count' => isset($segment['approximateMemberCount'])
                    ? (int) $segment['approximateMemberCount'] : null,
                'available' => $this->eligible($segment, $account),
            ])->values()->all();
    }

    /** @return list<array{urn: string, name: string, type: string, account: string, operation: string}> */
    public function selected(Campaign $campaign): array
    {
        $values = $campaign->targetingSet()->first()?->options['linkedin_segments'] ?? [];

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

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

        $accountUrn = LinkedInUrn::account((string) $campaign->ad_account_id);

        foreach ($values as $segment) {
            if (! is_array($segment)
                || ! preg_match('/^urn:li:adSegment:[0-9]+$/D', (string) ($segment['urn'] ?? ''))
                || trim((string) ($segment['name'] ?? '')) === ''
                || ($segment['type'] ?? null) !== 'RETARGETING'
                || ($segment['account'] ?? null) !== $accountUrn
                || ! in_array($segment['operation'] ?? null, ['include', 'exclude'], true)) {
                throw new RuntimeException('Saved LinkedIn audience segment 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 [];
        }

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

        foreach ($selected as $segment) {
            $id = substr($segment['urn'], strlen('urn:li:adSegment:'));
            $fresh = $this->linkedin->adSegment($account, $id);

            if (! $this->eligible($fresh, $account)
                || (string) $fresh['id'] !== $id
                || (string) $fresh['name'] !== $segment['name']) {
                throw new RuntimeException('A saved LinkedIn retargeting segment 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 [];
        }

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

        return array_map(function (array $segment) use ($account): array {
            $id = substr($segment['urn'], strlen('urn:li:adSegment:'));
            $fresh = $this->linkedin->adSegment($account, $id);
            $count = $this->eligible($fresh, $account) && (string) ($fresh['id'] ?? '') === $id
                && (string) $fresh['name'] === $segment['name']
                ? ($fresh['approximateMemberCount'] ?? null) : null;

            return [
                'urn' => $segment['urn'], 'name' => $segment['name'], 'operation' => $segment['operation'],
                'status' => is_numeric($count) ? 'fresh' : 'unavailable',
                'metric' => 'approximate_linkedin_segment_members',
                'members' => is_numeric($count) ? (int) $count : null,
            ];
        }, $selected);
    }

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

        if ($campaign->isPublished()
            || ! preg_match('/^urn:li:adSegment:([0-9]+)$/D', $urn, $matches)
            || ! in_array($operation, ['include', 'exclude'], true)) {
            throw new RuntimeException('Choose an include or exclude retargeting segment on a draft LinkedIn campaign.');
        }

        $fresh = $this->linkedin->adSegment($account, $matches[1]);

        if (! $this->eligible($fresh, $account) || (string) ($fresh['id'] ?? '') !== $matches[1]) {
            throw new RuntimeException('This LinkedIn retargeting segment 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, $fresh, $urn, $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['urn'] === $urn)) {
                throw new RuntimeException('This segment is already selected. Remove it before changing include or exclude.');
            }

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

            $selected[] = [
                'urn' => $urn, 'name' => (string) $fresh['name'], 'type' => 'RETARGETING',
                'account' => LinkedInUrn::account($account), 'operation' => $operation,
            ];
            $set->update([
                'options' => [...(array) ($set->options ?? []), 'linkedin_segments' => $selected],
                'revision' => $set->revision + 1,
            ]);
            $campaign->unsetRelation('targetingSet');

            return $set;
        });
    }

    public function remove(Campaign $campaign, string $urn, int $expectedRevision): TargetingSet
    {
        if ($campaign->platform !== 'linkedin' || $campaign->isPublished()) {
            throw new RuntimeException('Only a draft LinkedIn campaign can remove a retargeting segment.');
        }

        return DB::transaction(function () use ($campaign, $urn, $expectedRevision): TargetingSet {
            $set = TargetingSet::query()->where('campaign_id', $campaign->getKey())->lockForUpdate()->first()
                ?? throw new RuntimeException('This campaign has no retargeting segment 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 $segment): bool => $segment['urn'] !== $urn));

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

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

            return $set;
        });
    }

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

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

        return $account;
    }

    /** @param  array<string, mixed>  $segment */
    private function eligible(array $segment, string $account): bool
    {
        return preg_match('/^[0-9]+$/D', (string) ($segment['id'] ?? '')) === 1
            && trim((string) ($segment['name'] ?? '')) !== ''
            && ($segment['account'] ?? null) === LinkedInUrn::account($account)
            && ($segment['type'] ?? null) === 'RETARGETING'
            && ($segment['status'] ?? null) === 'READY';
    }
}
