<?php

namespace App\Campaigns\Publishing;

use App\Services\Meta\Meta;
use App\Services\Meta\MetaException;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Sleep;

/**
 * Pause a Meta campaign only after its ad set and ads exist.
 *
 * ads_activate_entity returns while StockPrices is still publishing the draft.
 * Pausing in that window is refused with 1815558, and the campaign is the only
 * object Ads Manager keeps. This reads every object, and pauses the campaign
 * once each one has a status. The reads after the first happen once the publish
 * response has already been sent, so the chat is not held for Meta's minute.
 */
class MetaDraftPause
{
    /** @var list<int> seconds between status reads after the publish response */
    public const WAIT_SECONDS = [15, 15, 30, 30];

    public function __construct(private readonly Meta $meta) {}

    /**
     * @param  list<array{id: string, type: string}>  $objects
     */
    public function pauseOnceCreated(string $adAccountId, array $objects, bool $pauseChildren = true): void
    {
        if ($this->attempt($adAccountId, $objects, $pauseChildren)) {
            return;
        }

        app()->terminating(function () use ($adAccountId, $objects, $pauseChildren): void {
            $this->resumeWhenCreated($adAccountId, $objects, $pauseChildren);
        });
    }

    /**
     * @param  list<array{id: string, type: string}>  $objects
     */
    public function resumeWhenCreated(string $adAccountId, array $objects, bool $pauseChildren = true): void
    {
        foreach (self::WAIT_SECONDS as $seconds) {
            Sleep::for($seconds)->seconds();

            if ($this->attempt($adAccountId, $objects, $pauseChildren)) {
                return;
            }
        }

        Log::critical('Meta campaign was published but its ad set and ads were never created, so it was not paused', [
            'ad_account_id' => $adAccountId,
            'missing' => $this->missing($adAccountId, $objects),
        ]);
    }

    /**
     * @param  list<array{id: string, type: string}>  $objects
     */
    private function attempt(string $adAccountId, array $objects, bool $pauseChildren): bool
    {
        $found = $this->found($adAccountId, $objects);
        $missing = array_values(array_filter(
            $objects,
            fn (array $object): bool => ! array_key_exists($object['id'], $found),
        ));

        if ($missing !== []) {
            Log::info('Meta campaign objects are not created yet, so the campaign is not paused', [
                'ad_account_id' => $adAccountId,
                'created' => $found,
                'missing' => array_map(
                    fn (array $object): array => ['id' => $object['id'], 'type' => $object['type']],
                    $missing,
                ),
            ]);

            return false;
        }

        Log::info('Meta campaign, ad set, and ads are created, pausing the campaign', [
            'ad_account_id' => $adAccountId,
            'created' => $found,
        ]);

        foreach ($objects as $object) {
            if ($object['type'] !== 'campaign' && ! $pauseChildren) {
                continue;
            }

            try {
                $this->meta->pauseCreatedObject($adAccountId, $object['id'], $object['type']);
            } catch (MetaException $exception) {
                if (! $exception->isDraftStillPublishing()) {
                    throw $exception;
                }

                Log::warning('Meta is still publishing the draft, so the pause waits for that publish', [
                    'ad_account_id' => $adAccountId,
                    'entity_id' => $object['id'],
                    'entity_type' => $object['type'],
                    'error' => $exception->getMessage(),
                ]);

                return false;
            }
        }

        return true;
    }

    /**
     * @param  list<array{id: string, type: string}>  $objects
     * @return array<string, array{id: string, type: string, status: string, effective_status: string}>
     */
    private function found(string $adAccountId, array $objects): array
    {
        $found = [];

        foreach ($objects as $object) {
            $status = $this->meta->objectStatus($object['id'], $adAccountId);

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

            $found[$object['id']] = [
                'id' => $object['id'],
                'type' => $object['type'],
                'status' => $status['status'],
                'effective_status' => $status['effective_status'],
            ];
        }

        return $found;
    }

    /**
     * @param  list<array{id: string, type: string}>  $objects
     * @return list<array{id: string, type: string}>
     */
    private function missing(string $adAccountId, array $objects): array
    {
        $found = $this->found($adAccountId, $objects);

        return array_values(array_map(
            fn (array $object): array => ['id' => $object['id'], 'type' => $object['type']],
            array_filter($objects, fn (array $object): bool => ! array_key_exists($object['id'], $found)),
        ));
    }
}
