<?php

namespace App\Services\Meta;

/**
 * Per-object failures inside a publish that the MCP still reported as a success.
 *
 * ads_activate_entity can return success while one ad set inside it failed.
 * That failure is the reason a later ad create is refused. The ad-create
 * message names the missing ad set and hides the cause.
 */
class PublishedObjectReport
{
    /**
     * @param  array<string, mixed>  $payload
     * @return list<array{id: string, type: string, message: string}>
     */
    public static function errors(array $payload): array
    {
        $found = [];

        self::visit($payload, $found);

        return $found;
    }

    /**
     * @param  array<string, mixed>  $node
     * @param  list<array{id: string, type: string, message: string}>  $found
     */
    private static function visit(array $node, array &$found): void
    {
        $message = self::message($node);
        $id = self::id($node);
        $type = self::type($node);

        if ($message !== null && ($id !== '' || $type !== '')) {
            $found[] = ['id' => $id, 'type' => $type, 'message' => $message];
        }

        foreach ($node as $key => $value) {
            if (! is_array($value)) {
                continue;
            }

            if (array_is_list($value)) {
                foreach ($value as $item) {
                    if (is_array($item)) {
                        self::visit($item, $found);
                    }
                }

                continue;
            }

            if (in_array($key, ['error', 'errors', 'result', 'results', 'objects', 'data', 'entities'], true)) {
                self::visit($value, $found);
            }
        }
    }

    /** @param  array<string, mixed>  $node */
    private static function message(array $node): ?string
    {
        $failed = ($node['success'] ?? null) === false || ($node['ok'] ?? null) === false;
        $message = $node['error_message'] ?? null;

        if (! is_string($message) || $message === '') {
            $error = $node['error'] ?? null;
            $message = is_array($error)
                ? ($error['error_message'] ?? $error['message'] ?? null)
                : (is_string($error) ? $error : null);
        }

        if (! is_string($message) || $message === '') {
            return null;
        }

        if ($failed || self::id($node) !== '' || self::type($node) !== '') {
            return $message;
        }

        return null;
    }

    /** @param  array<string, mixed>  $node */
    private static function id(array $node): string
    {
        foreach (['id', 'entity_id', 'object_id'] as $key) {
            if (filled($node[$key] ?? null)) {
                return (string) $node[$key];
            }
        }

        return '';
    }

    /** @param  array<string, mixed>  $node */
    private static function type(array $node): string
    {
        $type = strtolower((string) ($node['entity_type'] ?? $node['object_type'] ?? $node['type'] ?? ''));

        return match ($type) {
            'adset', 'ad_set' => 'ad_set',
            'adcampaign', 'ad_campaign' => 'campaign',
            'adcreative' => 'creative',
            default => $type,
        };
    }
}
