<?php

namespace App\Services\LinkedIn;

use App\Services\Platforms\Support\CallLogger;

/**
 * Unified facade for LinkedIn Ads.
 *
 * Coordinates LinkedIn operations through guardrails and audit logging.
 */
class LinkedIn
{
    public function __construct(
        private readonly LinkedInRestApi $api,
        private readonly CallLogger $log,
    ) {}

    /**
     * Attribute subsequent calls to a campaign draft in the audit trail.
     */
    public function on(?int $campaignId, ?string $actor): static
    {
        $this->log->attributeTo($campaignId, $actor);

        return $this;
    }

    /**
     * @return list<array<string,mixed>>
     */
    public function adAccounts(): array
    {
        return $this->api->adAccounts();
    }

    public function lifetimeDelivery(string $adAccountId, string $type, string $id, int $createdAtMs): array
    {
        return $this->api->lifetimeDelivery($adAccountId, $type, $id, $createdAtMs);
    }

    public function campaign(string $adAccountId, string $campaignId): array
    {
        return $this->api->campaign($adAccountId, $campaignId);
    }

    /**
     * @return list<array{urn: string, name: string}>
     */
    public function locationCandidates(string $adAccountId, string $query): array
    {
        return $this->api->locationCandidates($adAccountId, $query);
    }

    /**
     * @return list<array<string, mixed>>
     */
    public function professionalTargets(string $adAccountId, string $facet, ?string $query = null): array
    {
        return $this->api->professionalTargets($adAccountId, $facet, $query);
    }

    /**
     * @param  list<string>  $urns
     * @return list<array<string, mixed>>
     */
    public function targetingEntities(string $adAccountId, array $urns): array
    {
        return $this->api->targetingEntities($adAccountId, $urns);
    }

    /** @return list<string> */
    public function campaignConversions(string $adAccountId, string $campaignId): array
    {
        return $this->api->campaignConversions($adAccountId, $campaignId);
    }

    /** @param list<string> $desired */
    public function replaceCampaignConversions(string $adAccountId, string $campaignId, array $desired, ?array $expected = null): void
    {
        $this->api->replaceCampaignConversions($adAccountId, $campaignId, $desired, $expected);
    }

    /** @return list<array<string, mixed>> */
    public function conversions(string $adAccountId): array
    {
        return $this->api->conversions($adAccountId);
    }

    public function campaignGroup(string $adAccountId, string $groupId): array
    {
        return $this->api->campaignGroup($adAccountId, $groupId);
    }

    public function creative(string $adAccountId, string $creativeId): array
    {
        return $this->api->creative($adAccountId, $creativeId);
    }

    public function campaigns(string $adAccountId, ?string $pageToken = null, ?string $groupId = null): array
    {
        return $this->api->campaigns($adAccountId, $pageToken, $groupId);
    }

    public function campaignGroups(string $adAccountId, ?string $pageToken = null): array
    {
        return $this->api->campaignGroups($adAccountId, $pageToken);
    }

    /** @return array<string, mixed> */
    public function authoredPost(string $adAccountId, string $postUrn): array
    {
        return $this->api->authoredPost($adAccountId, $postUrn);
    }

    public function creatives(string $adAccountId, string $campaignId, ?string $pageToken = null): array
    {
        return $this->api->creatives($adAccountId, $campaignId, $pageToken);
    }

    /** @return list<array<string, mixed>> */
    public function adSegments(string $adAccountId): array
    {
        return $this->api->adSegments($adAccountId);
    }

    /** @return array<string, mixed> */
    public function adSegment(string $adAccountId, string $segmentId): array
    {
        return $this->api->adSegment($adAccountId, $segmentId);
    }

    /**
     * @param  string  $status  DRAFT or ACTIVE. LinkedIn takes no other value on
     *                          creation: PAUSED is refused with
     *                          "/CampaignGroup/status cannot be changed from
     *                          null to PAUSED", which is what this defaulted to.
     *                          The kill switch forced it back to DRAFT, so
     *                          LinkedIn publishing worked only while publishing
     *                          was disabled and broke at the first call the
     *                          moment it was enabled.
     */
    public function createCampaignGroup(string $adAccountId, string $name, string $status = 'DRAFT'): string
    {
        $response = $this->api->createCampaignGroup($adAccountId, [
            'name' => $name,
            'status' => $status,
        ]);

        return (string) ($response['id'] ?? '');
    }

    public function createCampaign(string $adAccountId, array $payload): string
    {
        $response = $this->api->createCampaign($adAccountId, $payload);

        return (string) ($response['id'] ?? '');
    }

    public function createCreative(string $adAccountId, array $payload): string
    {
        $response = $this->api->createCreative($adAccountId, $payload);

        return (string) ($response['id'] ?? '');
    }

    public function createPost(array $payload, ?string $adAccountId = null): string
    {
        $response = $this->api->createPost($payload, $adAccountId);

        return (string) ($response['id'] ?? '');
    }

    public function uploadImage(string $adAccountId, string $filePath, ?string $name = null, ?string $ownerUrn = null): string
    {
        return $this->api->uploadImage($adAccountId, $filePath, $name, $ownerUrn);
    }

    /**
     * Set any entity's status.
     *
     * publish() used to live here and set the campaign ACTIVE behind a config
     * check, which made going live a property of the environment rather than a
     * decision anybody made. Starting a campaign is now asked for in the chat and
     * approved on its own, and the levels below the campaign have to move with it,
     * so what this needs to expose is the general call rather than one verb.
     *
     * @param  array<string, mixed>  $fields
     * @param  list<string>  $deleteFields
     */
    public function updateEntity(string $adAccountId, string $entityType, string $entityId, array $fields, array $deleteFields = []): void
    {
        $this->api->updateEntity($adAccountId, $entityType, $entityId, $fields, $deleteFields);
    }

    public function pause(string $adAccountId, string $campaignId): void
    {
        $this->api->updateEntity($adAccountId, 'campaign', $campaignId, [
            'status' => 'PAUSED',
        ]);
    }

    /**
     * Change fields on a live campaign.
     *
     * publish() and pause() already went through updateEntity to set one field,
     * so the route existed and only the status ever used it. Named here rather
     * than left to callers reaching past this wrapper into the REST client,
     * which is what the wrapper is for: on() carries the campaign and actor
     * that make the call auditable.
     *
     * @param  array<string, mixed>  $fields
     */
    public function updateCampaign(string $adAccountId, string $campaignId, array $fields): void
    {
        $this->api->updateEntity($adAccountId, 'campaign', $campaignId, $fields);
    }

    public function delete(string $adAccountId, string $entityType, string $entityId): bool
    {
        return $this->api->delete($adAccountId, $entityType, $entityId);
    }
}
