<?php

namespace App\Campaigns\Manager\Readers;

use App\Campaigns\Manager\PlatformEntity;
use App\Campaigns\Manager\PlatformSnapshot;
use App\Campaigns\Manager\StructureReader;
use App\Models\Campaign;
use App\Services\LinkedIn\LinkedIn;
use App\Services\LinkedIn\LinkedInException;
use App\Services\LinkedIn\LinkedInUrn;
use RuntimeException;

/**
 * A LinkedIn campaign with the group above it and the sponsored creatives
 * below it. The group is the parent here, unlike every other platform, and a
 * change to it can reach sibling campaigns this product does not manage.
 */
class LinkedInStructureReader implements StructureReader
{
    /** Pages of creatives read before the snapshot is called incomplete. */
    private const int MOST_PAGES = 10;

    /**
     * Bookkeeping that changes on every write and says nothing about how the
     * campaign is set up. Kept out so a rename does not also report these.
     */
    private const array VOLATILE = ['changeAuditStamps', 'version', 'lastModified', 'lastModifiedAt', 'created', 'createdAt', 'id', 'name', 'status', 'account'];

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

    public function read(Campaign $campaign, ?string $actor = null): PlatformSnapshot
    {
        $campaignId = LinkedInUrn::numericId((string) $campaign->external_campaign_id)
            ?? throw new RuntimeException('LinkedIn campaign id must be numeric or a campaign URN.');
        $account = LinkedInUrn::numericId((string) $campaign->ad_account_id)
            ?? throw new RuntimeException('This LinkedIn campaign has no ad account recorded.');
        $linkedin = $this->linkedin->on($campaign->id, $actor);

        $live = $linkedin->campaign($account, $campaignId);

        if (LinkedInUrn::numericId((string) ($live['id'] ?? '')) !== $campaignId) {
            throw new RuntimeException('LinkedIn returned a different campaign than the one requested.');
        }

        $groupId = LinkedInUrn::numericId((string) ($live['campaignGroup'] ?? ''))
            ?? throw new RuntimeException('LinkedIn returned this campaign without a campaign group, so its structure cannot be verified.');
        $group = $linkedin->campaignGroup($account, $groupId);
        try {
            $live['conversion_rules'] = $linkedin->campaignConversions($account, $campaignId);
        } catch (LinkedInException $exception) {
            report($exception);
            $live['conversion_rules'] = null;
            $live['conversion_rules_error'] = $exception->getMessage();
        }

        $entities = [
            new PlatformEntity(
                type: 'campaign_group',
                externalId: $groupId,
                name: $group['name'] ?? null,
                status: $group['status'] ?? null,
                effectiveStatus: $this->serving($group),
                settings: $this->settings($group),
            ),
            new PlatformEntity(
                type: 'campaign',
                externalId: $campaignId,
                parentType: 'campaign_group',
                parentExternalId: $groupId,
                name: $live['name'] ?? null,
                status: $live['status'] ?? null,
                effectiveStatus: $this->serving($live),
                settings: $this->settings($live),
            ),
        ];

        $token = null;
        $pages = 0;

        do {
            $page = $linkedin->creatives($account, $campaignId, $token);
            $pages++;

            foreach ($page['elements'] ?? [] as $creative) {
                if (LinkedInUrn::numericId((string) ($creative['campaign'] ?? '')) !== $campaignId) {
                    throw new RuntimeException('LinkedIn returned a creative outside this campaign.');
                }

                $creativeId = LinkedInUrn::numericId((string) ($creative['id'] ?? ''));

                if ($creativeId === null) {
                    continue;
                }

                $entities[] = new PlatformEntity(
                    type: 'creative',
                    externalId: $creativeId,
                    parentType: 'campaign',
                    parentExternalId: $campaignId,
                    name: $creative['name'] ?? null,
                    status: $creative['intendedStatus'] ?? $creative['status'] ?? null,
                    effectiveStatus: isset($creative['isServing']) ? ($creative['isServing'] ? 'SERVING' : 'NOT_SERVING') : null,
                    settings: $this->settings($creative, ['campaign', 'intendedStatus', 'isServing']),
                );
            }

            $token = $page['next_page_token'] ?? null;
        } while ($token !== null && $pages < self::MOST_PAGES);

        return $token === null
            ? new PlatformSnapshot($entities)
            : new PlatformSnapshot($entities, ['creative'], [sprintf('LinkedIn has more than %d pages of creatives; the rest were not read.', self::MOST_PAGES)]);
    }

    /** @param  array<string, mixed>  $entity */
    private function serving(array $entity): ?string
    {
        $statuses = $entity['servingStatuses'] ?? null;

        return is_array($statuses) && $statuses !== [] ? (string) reset($statuses) : null;
    }

    /**
     * @param  array<string, mixed>  $entity
     * @param  list<string>  $alsoDrop
     * @return array<string, mixed>
     */
    private function settings(array $entity, array $alsoDrop = []): array
    {
        return array_diff_key($entity, array_flip([...self::VOLATILE, ...$alsoDrop]));
    }
}
