<?php

namespace App\Services\Meta;

use RuntimeException;
use Throwable;

class MetaException extends RuntimeException
{
    /** @param array<string, mixed> $diagnostics */
    public function __construct(
        string $message = '',
        int $code = 0,
        ?Throwable $previous = null,
        private readonly array $diagnostics = [],
    ) {
        parent::__construct($message, $code, $previous);
    }

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

    /**
     * The publish started by ads_activate_entity is still running.
     *
     * Error 1815558, and the "already publishing" refusal, both mean the draft
     * cannot be edited yet. They are not a reason to roll the campaign back.
     */
    public function isDraftStillPublishing(): bool
    {
        $subcode = (string) ($this->diagnostics['mcp_payload']['error_subcode'] ?? '');
        $message = strtolower($this->getMessage());

        return $subcode === '1815558'
            || str_contains($message, '1815558')
            || str_contains($message, 'already publishing')
            || str_contains($message, 'while it is publishing');
    }
}
