<?php

namespace App\Campaigns\Publishing;

use App\Models\Campaign;
use App\Models\PlatformConnection;
use App\Services\LinkedIn\LinkedIn;
use App\Services\LinkedIn\LinkedInRestApi;
use App\Services\Platforms\LinkedInAdapter;
use App\Services\Platforms\Support\CallLogger;
use Illuminate\Support\Facades\Log;
use Throwable;

/**
 * LinkedIn's implementation of campaign publishing.
 */
class LinkedInPublisher implements PlatformPublisher
{
    public function __construct(
        private readonly LinkedInAdapter $adapter,
    ) {}

    /**
     * @param  array<string,mixed>  $created
     * @return array<string,mixed>
     */
    public function create(Campaign $campaign, string $actor, array &$created): array
    {
        app(CallLogger::class)->attributeTo($campaign->id, $actor);
        $this->forgetChosenGroup($campaign);
        $existingGroupId = $campaign->external_ids['campaign_group_id'] ?? null;

        try {
            $campaignId = $this->adapter->createCampaign($campaign);
        } catch (Throwable $exception) {
            if (blank($existingGroupId) && $groupId = $campaign->refresh()->external_ids['campaign_group_id'] ?? null) {
                $created['campaign_group_id'] = $groupId;
            }

            throw $exception;
        }

        // The group the adapter made or reused, so rollback can remove it.
        // createCampaign() returns only the campaign id, so nothing here ever
        // knew a group had been created and rollback left it on the account.
        if (blank($existingGroupId) && $groupId = $campaign->refresh()->external_ids['campaign_group_id'] ?? null) {
            $created['campaign_group_id'] = $groupId;
        }

        $created['campaign_id'] = $campaignId;
        $campaign->update(['external_campaign_id' => $campaignId]);

        if ($campaign->objective === 'WEBSITE_CONVERSIONS') {
            $conversionId = (string) ($campaign->meta['linkedin_setup']['conversion']['id'] ?? '');
            if ($conversionId === '') {
                throw new \RuntimeException('Choose an enabled LinkedIn conversion rule before publishing.');
            }
            app(LinkedInRestApi::class)->associateConversion((string) $campaign->ad_account_id, $campaignId, $conversionId);
        }

        $created['ads'] = [];

        // Held before any ad is built, so each ad can be created ACTIVE and go
        // straight into review while LinkedIn keeps it off delivery. Where
        // nothing is confirmed to hold it, an ad stays a draft.
        $creativeStatus = $this->adapter->park($campaign->fresh()) ? 'ACTIVE' : 'DRAFT';

        // An ad that already has a creative on LinkedIn is left alone.
        //
        // This created one for every row every time, so a second publish - a
        // retry after a partial failure, or a creative swap that adds a row -
        // built a duplicate creative for each ad that was already live. LinkedIn
        // accepts that without complaint: two creatives, two ads, the same copy
        // twice on the same campaign, and the second id overwrote the first in our
        // own row so the original was left running with nothing pointing at it.
        //
        // Read from the database rather than a loaded relation, because the rows
        // were written by the previous publish and a relation loaded before it
        // would still say they were drafts.
        foreach ($campaign->ads()->orderBy('id')->get() as $ad) {
            if (filled($ad->external_creative_id)) {
                continue;
            }

            $creativeId = $this->adapter->createAd($campaign, $ad, $creativeStatus);
            $ad->update([
                'external_creative_id' => $creativeId,
                'external_ad_id' => $creativeId,
                'status' => 'published',
            ]);
            $created['ads'][] = [
                'ad_row' => $ad->id,
                'creative_id' => $creativeId,
                'ad_id' => $creativeId,
            ];
        }

        // Nothing is started here.
        //
        // This called $this->adapter->publish(), which sets the campaign ACTIVE,
        // so on LinkedIn alone publishing meant going live - and the only reason it
        // did not was a switch rewriting the status further down. Meta and Google
        // have never done this. A campaign is built and parked on every platform,
        // and starting it is its own approved decision.
        return $created;
    }

    /**
     * Undo whatever was created before the failure.
     *
     * @param  array<string,mixed>  $created
     */
    public function rollBack(Campaign $campaign, array $created, string $actor): array
    {
        // Only the ads this publish created.
        //
        // This walked every ad on the campaign and reset any that looked
        // published, which on a campaign that had published successfully before
        // meant clearing the ids of live LinkedIn creatives this attempt never
        // touched. The creative kept running and nothing local pointed at it any
        // more: not editable, not removable, not visible as ours. Acting on the
        // campaign's current state instead of on what this attempt actually did.
        //
        // $created is the record of this attempt, so it is the only thing here
        // entitled to be undone.
        $rows = collect((array) ($created['ads'] ?? []))
            ->pluck('ad_row')
            ->filter()
            ->all();

        if ($rows !== []) {
            $campaign->ads()->whereIn('id', $rows)->update([
                'external_creative_id' => null,
                'external_ad_id' => null,
                'status' => 'draft',
            ]);
        }

        // Remove what was created, newest first.
        //
        // This was an empty try block with a comment saying cleanup "could" go
        // here, so a publish that failed on ad two of three left a real
        // LinkedIn campaign and a real creative behind while our rows went back
        // to draft. The record said nothing had happened and the account said
        // otherwise, and external_campaign_id stayed set, so a retry
        // short-circuited at createCampaign() and never rebuilt the rest.
        //
        // Creatives before the campaign, because a campaign cannot be removed
        // while things hang off it. Each failure is logged and the next one
        // still tried: a rollback that stops at the first error leaves more
        // behind than one that keeps going.
        $adAccountId = $campaign->ad_account_id ?: PlatformConnection::sharedAccountId('linkedin', config('platforms.linkedin.ad_account_id'));

        if (blank($adAccountId)) {
            // Nothing can be removed without an account to remove it from, and
            // whatever create() made is still there. Named rather than reported
            // as a clean rollback.
            return array_values(array_filter([
                $created['campaign_group_id'] ?? null,
                $created['campaign_id'] ?? null,
                ...collect((array) ($created['ads'] ?? []))->pluck('creative_id')->all(),
            ]));
        }

        $left = [];

        foreach (array_reverse((array) ($created['ads'] ?? [])) as $ad) {
            $left = [...$left, ...$this->remove($adAccountId, 'creative', $ad['creative_id'] ?? null, $campaign)];
        }

        if (! empty($created['campaign_id'])) {
            $left = [...$left, ...$this->remove($adAccountId, 'campaign', $created['campaign_id'], $campaign)];

            $campaign->update(['external_campaign_id' => null]);
        }

        // The group last, because the campaign hangs off it, and only one this
        // publish actually created. A group reused from an earlier successful
        // publish is not ours to remove.
        if (! empty($created['campaign_group_id'])) {
            $left = [...$left, ...$this->remove($adAccountId, 'campaign_group', $created['campaign_group_id'], $campaign)];

            $campaign->update([
                'external_ids' => collect((array) ($campaign->external_ids ?? []))
                    ->except('campaign_group_id')
                    ->all(),
            ]);
        }

        return $left;
    }

    /**
     * Delete one thing, and carry on if it will not go.
     *
     * Reported rather than swallowed: something left on the account is worth
     * knowing about, because the next attempt will build alongside it. The id
     * comes back as well as going to the log, so the buyer can be told rather
     * than only the operator.
     *
     * @return list<string> the id, when it is still there
     */
    private function remove(string $adAccountId, string $type, ?string $id, Campaign $campaign): array
    {
        if (blank($id)) {
            return [];
        }

        try {
            $this->adapter->delete($adAccountId, $type, $id);

            return [];
        } catch (Throwable $e) {
            Log::warning('LinkedIn rollback left something behind', [
                'campaign' => $campaign->id,
                'type' => $type,
                'id' => $id,
                'error' => $e->getMessage(),
            ]);

            return [$id];
        }
    }

    /**
     * Send approved changes to the live campaign.
     *
     * This was an empty body under the comment "Live updates for LinkedIn".
     * CampaignUpdater moves its snapshot forward on a clean return, so every
     * edit to a published LinkedIn campaign was recorded as applied and none of
     * them was sent: the budget, the bid and the dates on LinkedIn stayed as
     * first published while our rows and the chat said they had changed. A
     * buyer raising a daily budget saw the new number everywhere except where
     * the money is spent.
     *
     * The work is the adapter's, which already knows how to shape a budget and
     * a bid for LinkedIn and is where create() builds the same fields.
     *
     * @param  array<string, array{from: mixed, to: mixed}>  $changes
     */
    public function update(Campaign $campaign, array $changes, string $actor): void
    {
        app(CallLogger::class)->attributeTo($campaign->id, $actor);
        if ($changes === []) {
            return;
        }

        $linkedin = app(LinkedIn::class)->on($campaign->id, $actor);
        $before = $linkedin->campaign((string) $campaign->ad_account_id, (string) $campaign->external_campaign_id);
        foreach ($changes as $field => $change) {
            if (($change['from'] ?? null) === null) {
                continue;
            }
            $remote = match ($field) {
                'budget' => $before[$campaign->usesLifetimeBudget() ? 'totalBudget' : 'dailyBudget']['amount'] ?? null,
                'bid_amount' => $before['unitCost']['amount'] ?? null,
                'name' => preg_replace('/^ARB-/', '', (string) ($before['name'] ?? '')),
                'bid_strategy' => str_starts_with((string) ($before['optimizationTargetType'] ?? ''), 'TARGET_') ? 'TARGET_COST'
                    : (str_starts_with((string) ($before['optimizationTargetType'] ?? ''), 'MAX_') ? 'AUTOMATED_BID' : 'MAXIMUM_BID'),
                'starts_at' => $before['runSchedule']['start'] ?? null,
                'ends_at' => $before['runSchedule']['end'] ?? null,
                default => $change['from'],
            };
            $matches = in_array($field, ['budget', 'bid_amount'], true)
                ? is_numeric($remote) && (float) $remote === (float) $change['from']
                : $remote === $change['from'];
            if (in_array($field, ['starts_at', 'ends_at'], true)) {
                $timestamp = $change['from'] instanceof \DateTimeInterface ? $change['from']->getTimestamp() : strtotime((string) $change['from']);
                $matches = $timestamp !== false && is_numeric($remote) && (int) $remote === $timestamp * 1000;
            }
            if (! $matches) {
                throw new \RuntimeException('LinkedIn settings changed since review. Refresh and approve the current baseline before editing.');
            }
        }
        $patch = $this->adapter->updateCampaign($campaign, $changes);
        $after = $linkedin->campaign((string) $campaign->ad_account_id, (string) $campaign->external_campaign_id);
        foreach ($patch as $field => $value) {
            if ($field === 'targetingCriteria') {
                $sent = is_array($value) ? $value : [];
                $got = is_array($after[$field] ?? null) ? $after[$field] : [];

                if (! $this->adapter->targetingWasConfirmed($sent, $got)) {
                    throw new \RuntimeException('LinkedIn accepted the edit but did not confirm its values. Local published state was not advanced; refresh before retrying.');
                }

                continue;
            }

            if (($after[$field] ?? null) != $value) {
                throw new \RuntimeException('LinkedIn accepted the edit but did not confirm its values. Local published state was not advanced; refresh before retrying.');
            }
        }
    }

    /**
     * Start the group, the campaign and every creative under it.
     *
     * Delegated to the adapter for the same reason create() is: the payload shapes
     * and the three different words LinkedIn uses for "live" are platform detail.
     * The creative ids come from our own rows rather than from the account, so a
     * creative we did not build is not switched on by us.
     */
    public function activate(Campaign $campaign, string $actor): void
    {
        app(CallLogger::class)->attributeTo($campaign->id, $actor);
        $this->adapter->activate($campaign, $campaign->ads()
            ->whereNotNull('external_creative_id')
            ->whereNotIn('status', ['paused', 'archived', 'deleted'])
            ->pluck('external_creative_id')
            ->map(strval(...))
            ->all());
    }

    /**
     * Every publish builds its own campaign group.
     *
     * A draft could once pick an existing group, and one picked before that
     * step was removed would otherwise still be built into. A group left from
     * an earlier failed attempt carries no choice and is reused as before.
     */
    private function forgetChosenGroup(Campaign $campaign): void
    {
        $meta = (array) $campaign->meta;
        if (isset($meta['linkedin_import']) || ! isset($meta['linkedin_setup']['campaign_group'])) {
            return;
        }

        $chosen = (string) ($meta['linkedin_setup']['campaign_group']['id'] ?? '');
        unset($meta['linkedin_setup']['campaign_group']);
        $externalIds = (array) $campaign->external_ids;
        if ($chosen !== 'new' && (string) ($externalIds['campaign_group_id'] ?? '') === $chosen) {
            unset($externalIds['campaign_group_id']);
        }

        $campaign->update(['meta' => $meta, 'external_ids' => $externalIds]);
    }

    /** And stop it, at the campaign. */
    public function pause(Campaign $campaign, string $actor): void
    {
        $linkedin = app(LinkedIn::class)->on($campaign->id, $actor);
        $live = $linkedin->campaign((string) $campaign->ad_account_id, (string) $campaign->external_campaign_id);
        $group = $linkedin->campaignGroup((string) $campaign->ad_account_id, (string) $live['campaignGroup']);
        if (in_array($live['status'] ?? null, ['DRAFT', 'PAUSED', 'ARCHIVED', 'COMPLETED', 'CANCELED', 'REMOVED'], true)
            || in_array($group['status'] ?? null, ['DRAFT', 'PAUSED'], true)) {
            $campaign->update(['meta' => [...(array) $campaign->meta, 'linkedin_state' => [
                'campaign_status' => $live['status'] ?? null, 'group_status' => $group['status'] ?? null,
                'refreshed_at' => now()->toIso8601String(),
            ]]]);

            return;
        }

        $this->adapter->pause($campaign);
    }

    /**
     * Not knowable here yet, so it says so rather than guessing.
     *
     * LinkedInRestApi can create a campaign group, a campaign, an ad and a
     * creative, and the adapter can activate and pause - there is no read for a
     * campaign's status anywhere in either. Returning false would be a lie the
     * caller cannot tell from a real answer, and it is the lie that offers to
     * start a campaign that is already spending. Null is the honest answer and
     * the caller falls back to local state.
     */
    public function isLive(Campaign $campaign, string $actor): ?bool
    {
        try {
            $linkedin = app(LinkedIn::class)->on($campaign->id, $actor);
            $live = $linkedin->campaign((string) $campaign->ad_account_id, (string) $campaign->external_campaign_id);
            $group = $linkedin->campaignGroup((string) $campaign->ad_account_id, (string) $live['campaignGroup']);

            if (! isset($live['status'], $group['status'])) {
                return null;
            }

            return $live['status'] === 'ACTIVE' && $group['status'] === 'ACTIVE';
        } catch (Throwable $exception) {
            Log::warning('LinkedIn live status unavailable', ['campaign' => $campaign->id, 'error' => $exception->getMessage()]);

            return null;
        }
    }
}
