<?php

namespace App\Campaigns;

use App\Campaigns\Platforms\LinkedInRules;
use App\Models\Asset;
use App\Models\Campaign;
use App\Models\User;
use App\Services\LinkedIn\LinkedIn;
use App\Services\LinkedIn\LinkedInUrn;
use App\Services\Platforms\LinkedInAdapter;
use RuntimeException;

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

    public function entity(Campaign $campaign, string $type, string $id, string $actor): array
    {
        if ($campaign->platform !== 'linkedin' || blank($campaign->ad_account_id)) {
            throw new RuntimeException('Open a published LinkedIn campaign with a verified account first.');
        }

        $api = $this->linkedin->on($campaign->id, $actor);
        $numeric = LinkedInUrn::numericId($id);
        if ($numeric === null) {
            throw new RuntimeException('Choose an exact LinkedIn entity ID from the live structure.');
        }
        if (! $campaign->isPublished()) {
            if ($type === 'campaign_group' && blank($campaign->external_campaign_id)
                && $numeric === LinkedInUrn::numericId((string) ($campaign->external_ids['campaign_group_id'] ?? ''))) {
                return $api->campaignGroup((string) $campaign->ad_account_id, $id);
            }
            throw new RuntimeException('This campaign has no live entity to manage.');
        }
        $parent = $api->campaign((string) $campaign->ad_account_id, (string) $campaign->external_campaign_id);

        if ($type === 'campaign' && $numeric === LinkedInUrn::numericId((string) $campaign->external_campaign_id)) {
            return $parent;
        }
        if ($type === 'campaign_group' && $numeric === LinkedInUrn::numericId((string) ($parent['campaignGroup'] ?? ''))) {
            return $api->campaignGroup((string) $campaign->ad_account_id, $id);
        }
        if (in_array($type, ['ad', 'creative'], true)) {
            $creative = $api->creative((string) $campaign->ad_account_id, $id);
            if (LinkedInUrn::numericId((string) ($creative['campaign'] ?? '')) === LinkedInUrn::numericId((string) $campaign->external_campaign_id)) {
                return $creative;
            }
        }

        throw new RuntimeException('This entity is not part of the campaign in focus. Nothing was changed.');
    }

    public function update(Campaign $campaign, string $type, string $id, array $fields, string $actor): array
    {
        $entity = $this->entity($campaign, $type, $id, $actor);
        $api = $this->linkedin->on($campaign->id, $actor);
        $type = $type === 'ad' ? 'creative' : $type;
        $statusField = $type === 'creative' ? 'intendedStatus' : 'status';
        if ($type === 'creative' && array_intersect(array_keys($fields), ['headline', 'primary_text', 'description', 'cta', 'asset_id']) !== []) {
            return $this->replaceCreative($campaign, $id, $fields, $actor);
        }
        $allowed = ['name', $statusField];
        if ($fields === [] || array_diff(array_keys($fields), $allowed) !== []) {
            throw new RuntimeException('Only name and the supported status field can be changed here. Campaign budgets and dates use push_changes; creative content requires replacement.');
        }
        if (isset($fields['name']) && (trim((string) $fields['name']) === '' || strlen((string) $fields['name']) > 200)) {
            throw new RuntimeException('Choose an entity name between 1 and 200 bytes.');
        }
        if (isset($fields['name'])) {
            $fields['name'] = trim((string) $fields['name']);
        }
        if (isset($fields[$statusField]) && ! in_array($fields[$statusField], ['ACTIVE', 'PAUSED', 'ARCHIVED'], true)) {
            throw new RuntimeException('Choose ACTIVE, PAUSED, or ARCHIVED.');
        }
        if ($type === 'campaign_group' && isset($fields[$statusField])) {
            $children = $api->campaigns((string) $campaign->ad_account_id, null, $id);
            if ($children['next_page_token'] !== null || collect($children['elements'])->contains(fn (array $child): bool => LinkedInUrn::numericId((string) $child['id']) !== LinkedInUrn::numericId((string) $campaign->external_campaign_id))) {
                throw new RuntimeException('This group contains other campaigns. Change those campaigns separately; a shared group status cannot be changed from one campaign.');
            }
        }
        if (($entity[$statusField] ?? null) === 'DRAFT' && ($fields[$statusField] ?? null) === 'PAUSED') {
            return ['id' => $id, 'state' => 'DRAFT', 'changed' => false, 'note' => 'Already draft and not eligible for delivery. No status transition was sent.'];
        }

        $api->updateEntity((string) $campaign->ad_account_id, $type, $id, $fields);
        $fresh = $this->entity($campaign, $type, $id, $actor);
        foreach ($fields as $field => $value) {
            if (($fresh[$field] ?? null) !== $value) {
                throw new RuntimeException('LinkedIn accepted the request, but its read-back value differed from the requested value; it may have been normalized. Refresh before retrying; local state was not advanced.');
            }
        }
        $this->remember($campaign, $type, $id, $fresh);
        if ($type === 'creative' && isset($fields[$statusField])) {
            $campaign->ads()->whereIn('external_creative_id', [$id, LinkedInUrn::creative($id)])
                ->update(['status' => strtolower($fields[$statusField])]);
            $replacementKey = LinkedInUrn::creative($id);
            if ($fields[$statusField] === 'ACTIVE' && isset($campaign->fresh()->meta['linkedin_replacements'][$replacementKey])) {
                $replacement = $campaign->fresh()->meta['linkedin_replacements'][$replacementKey];
                $oldId = (string) $replacement['original_creative_id'];
                $old = $this->entity($campaign, 'creative', $oldId, $actor);
                if (($old['intendedStatus'] ?? null) === 'ACTIVE') {
                    $this->update($campaign, 'creative', $oldId, ['intendedStatus' => 'PAUSED'], $actor);
                }
            }
        }

        return ['id' => $id, 'changed' => true, 'entity' => $fresh];
    }

    private function replaceCreative(Campaign $campaign, string $id, array $fields, string $actor): array
    {
        $allowed = ['headline', 'primary_text', 'description', 'cta', 'asset_id', 'name'];
        if (array_diff(array_keys($fields), $allowed) !== []) {
            throw new RuntimeException('Content replacement cannot be combined with a status change.');
        }
        $original = $campaign->ads()->whereIn('external_creative_id', [$id, LinkedInUrn::creative($id)])->first();
        if ($original === null) {
            throw new RuntimeException('This creative has no local copy/asset baseline. Import its content before requesting replacement.');
        }
        $values = [...$original->only(['headline', 'primary_text', 'description', 'cta', 'asset_id', 'ad_set_id']),
            ...array_intersect_key($fields, array_flip(['headline', 'primary_text', 'description', 'cta', 'asset_id']))];
        $rules = app(LinkedInRules::class);
        if (blank($values['headline']) || mb_strlen((string) $values['headline']) > 200
            || blank($values['primary_text']) || mb_strlen((string) $values['primary_text']) > 3000
            || ! in_array($values['cta'], $rules->callsToAction(), true)) {
            throw new RuntimeException('Replacement copy or call-to-action violates LinkedIn limits.');
        }
        $asset = Asset::find($values['asset_id']);
        if ($asset === null || (string) $asset->owner_id !== (string) $campaign->user_id
            || $asset->owner_type !== User::class || blank($asset->refFor('linkedin', (string) $campaign->ad_account_id)?->reference())) {
            throw new RuntimeException('Choose a creative owned by this campaign user and uploaded to its LinkedIn account first.');
        }
        if ($original->asset?->kind !== $asset->kind) {
            throw new RuntimeException('LinkedIn creative replacement cannot change the campaign media format.');
        }
        $reference = (string) $asset->refFor('linkedin', (string) $campaign->ad_account_id)?->reference();
        if (! str_starts_with($reference, 'urn:li:image:') && ! str_starts_with($reference, 'urn:li:video:')) {
            throw new RuntimeException('Prepare an image or video reference through review_assets first. An old share alone cannot carry replacement copy.');
        }
        if ($asset->kind === 'video' && ($campaign->meta['linkedin_video_statuses'][$reference]['status'] ?? null) !== 'AVAILABLE') {
            throw new RuntimeException('The replacement video is not confirmed AVAILABLE. Refresh asset review first.');
        }
        $ad = $campaign->ads()->create([...$values, 'status' => 'draft']);
        try {
            $newId = (new LinkedInAdapter(linkedIn: $this->linkedin->on($campaign->id, $actor)))->createAd($campaign, $ad);
        } catch (\Throwable $exception) {
            $ad->delete();
            throw $exception;
        }
        $ad->update(['external_creative_id' => $newId, 'external_ad_id' => $newId, 'status' => 'published']);
        $meta = (array) $campaign->fresh()->meta;
        $replacements = (array) ($meta['linkedin_replacements'] ?? []);
        $replacements[LinkedInUrn::creative($newId)] = ['original_creative_id' => LinkedInUrn::creative($id), 'ad_row' => $ad->getKey()];
        $campaign->update(['meta' => [...$meta, 'linkedin_replacements' => $replacements]]);

        return ['changed' => false, 'replacement_staged' => true, 'original_creative_id' => LinkedInUrn::creative($id),
            'replacement_creative_id' => $newId, 'note' => 'Replacement created DRAFT; original remains unchanged. Approve activating the replacement to pause its original after confirmed activation.'];
    }

    public function delivery(Campaign $campaign, string $type, string $id, string $actor): array
    {
        return $this->deliveryFor($campaign, $type, $id, $actor, $this->entity($campaign, $type, $id, $actor));
    }

    private function deliveryFor(Campaign $campaign, string $type, string $id, string $actor, array $entity): array
    {
        $created = (int) ($entity['createdAt'] ?? $entity['changeAuditStamps']['created']['time'] ?? 0);
        $delivery = $this->linkedin->on($campaign->id, $actor)->lifetimeDelivery((string) $campaign->ad_account_id, $type, $id, $created);

        return [...$delivery, 'currency' => $campaign->currency ?: 'unknown'];
    }

    public function delete(Campaign $campaign, string $type, string $id, string $actor, bool $deleteEvenThoughDelivered = false): array
    {
        $entity = $this->entity($campaign, $type, $id, $actor);
        $delivery = $this->deliveryFor($campaign, $type, $id, $actor, $entity);
        $api = $this->linkedin->on($campaign->id, $actor);
        if (! $deleteEvenThoughDelivered && ($delivery['spend'] > 0 || $delivery['impressions'] > 0)) {
            throw new RuntimeException(sprintf('This has delivered %.2f %s and %d impressions. Nothing was deleted; report those numbers and request a second confirmation.',
                $delivery['spend'], $delivery['currency'], $delivery['impressions']));
        }
        $type = $type === 'ad' ? 'creative' : $type;
        if ($type !== 'creative') {
            $children = $type === 'campaign'
                ? $api->creatives((string) $campaign->ad_account_id, $id)
                : $api->campaigns((string) $campaign->ad_account_id, null, $id);
            if ($children['elements'] !== [] || $children['next_page_token'] !== null) {
                throw new RuntimeException('This parent still has children. Review and remove them separately; no siblings or reused group will be deleted implicitly.');
            }
        }
        $statusField = $type === 'creative' ? 'intendedStatus' : 'status';
        $draft = ($entity[$statusField] ?? null) === 'DRAFT';
        if (! $draft) {
            $api->updateEntity((string) $campaign->ad_account_id, $type, $id, [$statusField => 'PENDING_DELETION']);
            $fresh = $this->entity($campaign, $type, $id, $actor);
            if (! in_array($fresh[$statusField] ?? null, ['PENDING_DELETION', 'REMOVED'], true)) {
                throw new RuntimeException('Deletion outcome is not confirmed. External IDs were retained; refresh before retrying.');
            }
            $this->remember($campaign, $type, $id, $fresh);

            return ['id' => $id, 'deleted' => false, 'pending_deletion' => true, 'entity' => $fresh];
        }
        if (! $api->delete((string) $campaign->ad_account_id, $type, $id)) {
            throw new RuntimeException('LinkedIn did not confirm deletion. External IDs were retained.');
        }
        $this->remember($campaign, $type, $id, [$statusField => 'REMOVED']);
        if ($type === 'campaign') {
            $campaign->update(['external_campaign_id' => null, 'activated_at' => null, 'status' => 'draft']);
        } elseif ($type === 'creative') {
            $campaign->ads()->whereIn('external_creative_id', [$id, LinkedInUrn::creative($id)])
                ->update(['external_creative_id' => null, 'external_ad_id' => null, 'status' => 'draft']);
            $external = (array) $campaign->fresh()->external_ids;
            $external['ads'] = array_values(array_filter((array) ($external['ads'] ?? []), fn (array $ad): bool => LinkedInUrn::numericId((string) ($ad['creative_id'] ?? '')) !== LinkedInUrn::numericId($id)));
            $campaign->update(['external_ids' => $external]);
        } elseif ($type === 'campaign_group') {
            $external = (array) $campaign->fresh()->external_ids;
            unset($external['campaign_group_id']);
            $campaign->update(['external_ids' => $external]);
        }

        return ['id' => $id, 'deleted' => true, 'pending_deletion' => false];
    }

    private function remember(Campaign $campaign, string $type, string $id, array $entity): void
    {
        $meta = (array) $campaign->fresh()->meta;
        $entities = (array) ($meta['linkedin_entities'] ?? []);
        $entities[$type.':'.$id] = ['entity' => $entity, 'refreshed_at' => now()->toIso8601String()];
        $campaign->update(['meta' => [...$meta, 'linkedin_entities' => $entities], 'last_synced_at' => now()]);
    }
}
