<?php

namespace App\Campaigns\Manager\Editing\Writers;

use App\Campaigns\LinkedInManagement;
use App\Campaigns\Manager\Editing\AdvancedEditFields;
use App\Campaigns\Manager\Editing\EditCapabilities;
use App\Campaigns\Manager\Editing\EditRefused;
use App\Campaigns\Manager\Editing\EntityWriter;
use App\Models\Campaign;
use App\Models\CampaignPlatformEntity;
use App\Services\LinkedIn\LinkedIn;
use App\Services\LinkedIn\LinkedInUrn;
use App\Support\CurrencyMinorUnits;
use Throwable;

/**
 * Names and statuses on every level; daily budget, total budget, bid strategy
 * (optimizationTargetType), unit cost and run dates on a campaign. A
 * creative's status is its intendedStatus.
 * Campaign fields use one partial update. Conversion associations require
 * separate native calls and fresh readback if any call fails.
 *
 * LinkedIn keeps money as {amount, currencyCode}. The currency is the one the
 * platform reported for that object, never assumed.
 *
 * A campaign group can hold campaigns this product does not manage, and its
 * new name shows on all of them; the wizard says so before anything is sent.
 * Group budgets are not offered for the same reason.
 *
 * runSchedule is replaced whole by $set, so whichever of start and end is not
 * being changed is sent back as LinkedIn reported it, and an open end stays open.
 */
class LinkedInEntityWriter implements EntityWriter
{
    private const array CAMPAIGN_COPY_FIELDS = [
        'name', 'associatedEntity', 'audienceExpansionEnabled', 'campaignGroup', 'costType',
        'creativeSelection', 'dailyBudget', 'locale', 'objectiveType', 'offsiteDeliveryEnabled',
        'offsitePreferences', 'runSchedule', 'targetingCriteria', 'totalBudget', 'type', 'unitCost',
        'optimizationTargetType', 'format', 'pacingStrategy', 'connectedTelevisionOnly',
        'optimizationPreference', 'politicalIntent', 'storyDeliveryEnabled',
    ];

    private const array CAMPAIGN_READ_ONLY = [
        'account', 'accountInfo', 'associatedEntityInfo', 'campaignGroupInfo', 'id', 'status',
        'version', 'versionTag', 'changeAuditStamps', 'createdAt', 'lastModifiedAt', 'test', 'servingStatuses',
    ];

    /** @var array<string, list<string>> */
    private const array FIELDS = [
        'campaign_group' => ['name', 'status'],
        'campaign' => ['name', 'status', 'daily_budget', 'total_budget', 'bid_strategy', 'unit_cost', 'start_time', 'end_time', ...AdvancedEditFields::LINKEDIN],
        'creative' => ['name', 'status'],
    ];

    /** @var array<string, string> */
    private const array MONEY = [
        'daily_budget' => 'dailyBudget',
        'total_budget' => 'totalBudget',
        'unit_cost' => 'unitCost',
    ];

    public function __construct(
        private readonly LinkedIn $linkedin,
        private readonly LinkedInManagement $management,
    ) {}

    public function write(Campaign $campaign, CampaignPlatformEntity $entity, array $patch, string $actor): void
    {
        $allowed = self::FIELDS[$entity->entity_type] ?? [];

        if ($patch === [] || array_diff(array_keys($patch), $allowed) !== []) {
            throw new EditRefused(sprintf('Only %s can be changed on a LinkedIn %s from here.', implode(', ', $allowed) ?: 'nothing', str_replace('_', ' ', $entity->entity_type)));
        }
        if (array_key_exists('conversion_rules', $patch)) {
            if (count($patch) !== 1 || ! is_array($patch['conversion_rules']) || ! is_array(data_get($entity->settings, 'conversion_rules'))) {
                throw new EditRefused('Conversion-rule associations must be reviewed separately.');
            }
            $this->linkedin->on($campaign->id, $actor)->replaceCampaignConversions(
                (string) $campaign->ad_account_id, $entity->external_id, AdvancedEditFields::normalize('conversion_rules', $patch['conversion_rules']),
                data_get($entity->settings, 'conversion_rules'),
            );

            return;
        }

        $currency = EditCapabilities::currency($entity);
        $set = [];
        $delete = [];

        foreach ($patch as $field => $value) {
            if (in_array($field, ['targeting_criteria', 'audience_expansion', 'offsite_delivery'], true)) {
                if ($field === 'offsite_delivery' && ! (bool) $value && data_get($entity->settings, 'connectedTelevisionOnly') === true) {
                    throw new EditRefused('Connected TV campaigns require LinkedIn Audience Network delivery.');
                }
                $set[AdvancedEditFields::path($field)] = $field === 'targeting_criteria'
                    ? AdvancedEditFields::normalize($field, $value)
                    : (bool) $value;

                continue;
            }
            if ($field === 'frequency_optimization') {
                if ($reason = AdvancedEditFields::refusal($entity, $field)) {
                    throw new EditRefused($reason);
                }
                $preference = AdvancedEditFields::normalize($field, $value);
                if ($preference === []) {
                    $delete[] = 'optimizationPreference';
                } else {
                    $set['optimizationPreference'] = ['frequencyOptimizationPreference' => $preference];
                }

                continue;
            }

            if ($field === 'name') {
                $set['name'] = (string) $value;

                continue;
            }

            if ($field === 'status') {
                if (! in_array($value, ['ACTIVE', 'PAUSED', 'ARCHIVED'], true)) {
                    throw new EditRefused('Choose active, paused or archived.');
                }

                if ($entity->entity_type === 'campaign_group') {
                    $this->assertGroupHoldsOnly($campaign, $entity, $actor);
                }

                $set[$entity->entity_type === 'creative' ? 'intendedStatus' : 'status'] = $value;

                continue;
            }

            // Sent in the same $set as a new unit cost, which LinkedIn asks for
            // when the two change together.
            if ($field === 'bid_strategy') {
                if (! is_string($value) || ! array_key_exists($value, EditCapabilities::strategyOptions($entity))) {
                    throw new EditRefused('LinkedIn does not allow that bid strategy for this objective.');
                }

                $set['optimizationTargetType'] = $value;

                continue;
            }

            if (EditCapabilities::isSchedule($field)) {
                $set['runSchedule'] = $this->runSchedule($entity, $patch);

                continue;
            }

            $set[self::MONEY[$field]] = [
                'amount' => number_format((float) $value, CurrencyMinorUnits::decimals($currency), '.', ''),
                'currencyCode' => $currency,
            ];
        }

        $api = $this->linkedin->on($campaign->id, $actor);
        if ($delete !== []) {
            $api->updateEntity((string) $campaign->ad_account_id, $entity->entity_type, $entity->external_id, $set, $delete);

            return;
        }
        $api->updateEntity(
            (string) $campaign->ad_account_id,
            $entity->entity_type,
            $entity->external_id,
            $set,
        );
    }

    /**
     * @param  array<string, mixed>  $patch
     * @return array{start: int, end?: int}
     */
    private function runSchedule(CampaignPlatformEntity $entity, array $patch): array
    {
        $start = $patch['start_time'] ?? data_get($entity->settings, 'runSchedule.start');
        $end = $patch['end_time'] ?? data_get($entity->settings, 'runSchedule.end');

        if (! is_numeric($start)) {
            throw new EditRefused('LinkedIn did not report when this campaign starts, so its schedule was not sent.');
        }

        return is_numeric($end) ? ['start' => (int) $start, 'end' => (int) $end] : ['start' => (int) $start];
    }

    /**
     * A group's status stops or starts every campaign in it, so it is changed
     * from here only when this campaign is the only one inside.
     */
    private function assertGroupHoldsOnly(Campaign $campaign, CampaignPlatformEntity $entity, string $actor): void
    {
        $children = $this->linkedin->on($campaign->id, $actor)->campaigns((string) $campaign->ad_account_id, null, $entity->external_id);
        $own = LinkedInUrn::numericId((string) $campaign->external_campaign_id);

        if ($children['next_page_token'] !== null
            || collect($children['elements'])->contains(fn (array $child): bool => LinkedInUrn::numericId((string) $child['id']) !== $own)) {
            throw new EditRefused('This group holds other campaigns too. Change those campaigns one by one; the group status is not changed from one campaign.');
        }
    }

    public function delivery(Campaign $campaign, CampaignPlatformEntity $entity, string $actor): array
    {
        $seen = $this->management->delivery($campaign, $entity->entity_type, $entity->external_id, $actor);

        return ['spend' => (float) $seen['spend'], 'impressions' => (int) $seen['impressions']];
    }

    /**
     * Through the chat's own delete, which confirms the object is this
     * campaign's, refuses a parent that still has children, and removes a draft
     * outright but only marks anything that has run for deletion. Delivery has
     * already been shown and acknowledged in the wizard, so it is not asked twice.
     */
    public function delete(Campaign $campaign, CampaignPlatformEntity $entity, string $actor): bool
    {
        $result = $this->management->delete($campaign, $entity->entity_type, $entity->external_id, $actor, deleteEvenThoughDelivered: true);

        return (bool) ($result['deleted'] ?? false);
    }

    public function duplicate(Campaign $campaign, CampaignPlatformEntity $entity, string $actor): string
    {
        if (! in_array($entity->entity_type, ['campaign', 'creative'], true)) {
            throw new EditRefused('Copy a LinkedIn campaign or sponsored creative, not its shared group.');
        }
        $api = $this->linkedin->on($campaign->id, $actor);
        $account = (string) $campaign->ad_account_id;
        $source = $this->management->entity($campaign, $entity->entity_type, $entity->external_id, $actor);
        if ($entity->entity_type === 'creative') {
            $payload = $this->creativeCopyPayload($source, (string) $campaign->external_campaign_id);
            $id = $this->createdId($api->createCreative($account, $payload));
            try {
                $this->verifyCopy($api->creative($account, $id), $payload);
            } catch (Throwable $exception) {
                $this->rollbackCopy($api, $account, null, [$id], $exception);
            }

            return $id;
        }

        if (array_diff(array_keys($source), [...self::CAMPAIGN_COPY_FIELDS, ...self::CAMPAIGN_READ_ONLY]) !== []) {
            throw new EditRefused('This campaign contains settings not yet supported for lossless reconstruction. Nothing was copied.');
        }
        foreach (['campaignGroup', 'objectiveType', 'type', 'costType', 'targetingCriteria', 'locale'] as $required) {
            if (blank($source[$required] ?? null)) {
                throw new EditRefused('LinkedIn did not report the campaign '.$required.' needed to reconstruct it.');
            }
        }
        $conversions = $api->campaignConversions($account, $entity->external_id);
        $eligible = array_map(fn (array $row): string => 'urn:lla:llaPartnerConversion:'.LinkedInUrn::numericId((string) $row['id']), $api->conversions($account));
        if (array_diff($conversions, $eligible) !== []) {
            throw new EditRefused('Some original conversion rules are no longer enabled for this account. Resolve them before copying.');
        }
        $creativePayloads = [];
        $pages = 0;
        $token = null;
        do {
            $page = $api->creatives($account, $entity->external_id, $token);
            $pages++;
            foreach ($page['elements'] as $creative) {
                if (! in_array($creative['intendedStatus'] ?? null, ['REMOVED', 'PENDING_DELETION', 'CANCELED'], true)) {
                    $creativePayloads[] = $this->creativeCopyPayload($creative, $entity->external_id);
                }
            }
            $token = $page['next_page_token'];
            if ($token !== null && $pages >= 10) {
                throw new EditRefused('Too many creatives to reconstruct this campaign completely.');
            }
        } while ($token !== null);
        $payload = array_intersect_key($source, array_flip(self::CAMPAIGN_COPY_FIELDS));
        $payload['name'] = self::copyName((string) ($source['name'] ?? 'Campaign'));
        $payload['status'] = 'DRAFT';
        $schedule = (array) ($payload['runSchedule'] ?? []);
        if (isset($schedule['end']) && (int) $schedule['end'] <= now()->getTimestampMs()) {
            throw new EditRefused('This campaign has ended. Its end date cannot be preserved on a new copy.');
        }
        $payload['runSchedule'] = [...$schedule, 'start' => max((int) ($schedule['start'] ?? 0), now()->getTimestampMs())];
        $copyId = $this->createdId($api->createCampaign($account, $payload));
        $created = [];
        try {
            if ($conversions !== []) {
                $api->replaceCampaignConversions($account, $copyId, $conversions);
            }
            foreach ($creativePayloads as $creativePayload) {
                $creativePayload['campaign'] = LinkedInUrn::campaign($copyId);
                $id = $this->createdId($api->createCreative($account, $creativePayload));
                $created[] = $id;
                $this->verifyCopy($api->creative($account, $id), $creativePayload);
            }
            $this->verifyCopy($api->campaign($account, $copyId), $payload);
            if ($api->campaignConversions($account, $copyId) !== $conversions) {
                throw new EditRefused('LinkedIn did not confirm the copied conversion associations.');
            }
        } catch (Throwable $exception) {
            $this->rollbackCopy($api, $account, $copyId, $created, $exception);
        }

        return $copyId;
    }

    /** @param array<string, mixed> $source
     * @return array<string, mixed>
     */
    private function creativeCopyPayload(array $source, string $campaignId): array
    {
        if (LinkedInUrn::numericId((string) ($source['campaign'] ?? '')) !== LinkedInUrn::numericId($campaignId)) {
            throw new EditRefused('LinkedIn returned a creative outside the original campaign.');
        }
        $content = $source['content'] ?? null;
        if (! is_array($content) || count($content) !== 1) {
            throw new EditRefused('LinkedIn did not report one complete creative content type.');
        }
        foreach (['standardUpdateAd', 'videoAd', 'standardUpdate', 'video'] as $enriched) {
            if (isset($content[$enriched]['reference'])) {
                $content = ['reference' => $content[$enriched]['reference']];
            }
        }
        if (array_key_exists('reference', $content)) {
            if (! is_string($content['reference']) || ! preg_match('/^urn:li:(share|ugcPost|adInMailContent):[0-9]+$/D', $content['reference'])) {
                throw new EditRefused('LinkedIn did not return a usable sponsored-content reference.');
            }
        } elseif (! is_array(reset($content)) || reset($content) === []) {
            throw new EditRefused('LinkedIn did not return complete native creative content.');
        }

        return [
            'campaign' => LinkedInUrn::campaign($campaignId),
            'name' => self::copyName((string) ($source['name'] ?? 'Sponsored creative')),
            'content' => $content,
            'intendedStatus' => 'DRAFT',
            ...array_intersect_key($source, ['leadgenCallToAction' => true]),
        ];
    }

    private static function copyName(string $name): string
    {
        return mb_strcut($name, 0, 180, 'UTF-8').' - copy';
    }

    private function createdId(string $value): string
    {
        return LinkedInUrn::numericId($value)
            ?? throw new EditRefused('LinkedIn accepted creation without returning an object ID. Check the account before retrying.');
    }

    /** @param array<string, mixed> $actual
     * @param  array<string, mixed>  $expected
     */
    private function verifyCopy(array $actual, array $expected): void
    {
        foreach ($expected as $field => $value) {
            if ($field === 'content' && isset($value['reference'])) {
                foreach (['standardUpdateAd', 'videoAd', 'standardUpdate', 'video'] as $enriched) {
                    if (isset($actual[$field][$enriched]['reference'])) {
                        $actual[$field] = ['reference' => $actual[$field][$enriched]['reference']];
                    }
                }
            }
            if (($actual[$field] ?? null) != $value) {
                throw new EditRefused('LinkedIn did not confirm copied '.$field.'. The incomplete draft is being removed.');
            }
        }
    }

    /** @param list<string> $creatives */
    private function rollbackCopy(LinkedIn $api, string $account, ?string $campaignId, array $creatives, Throwable $cause): never
    {
        $left = [];
        foreach ([...array_map(fn (string $id): array => ['creative', $id], array_reverse($creatives)), ...($campaignId !== null ? [['campaign', $campaignId]] : [])] as [$type, $id]) {
            try {
                if (! $api->delete($account, $type, $id)) {
                    $left[] = $type.':'.$id;
                }
            } catch (Throwable $exception) {
                report($exception);
                $left[] = $type.':'.$id;
            }
        }
        throw new EditRefused($cause->getMessage().($left === [] ? ' Incomplete copies were removed.' : ' Cleanup is incomplete; review these DRAFT objects: '.implode(', ', $left)), previous: $cause);
    }
}
