<?php

namespace EasyLinkAutomations\Actions\Brevo;

if (!defined('ABSPATH')) {
    exit;
}

final class BrevoRequestHelper
{
    private const API_BASE = 'https://api.brevo.com/v3';

    public static function url(string $path, array $query = []): string
    {
        $url = self::API_BASE . '/' . ltrim($path, '/');

        if (!empty($query)) {
            $url .= '?' . http_build_query($query);
        }

        return $url;
    }

    public static function headers(string $token, bool $json = false): array
    {
        $headers = [
            'api-key' => $token,
        ];

        if ($json) {
            $headers['Content-Type'] = 'application/json';
        }

        return $headers;
    }

    public static function failureMessage(int $statusCode, mixed $responseBody): string
    {
        $message = 'Unknown error';

        if (is_array($responseBody)) {
            if (isset($responseBody['message'])) {
                $message = (string) $responseBody['message'];
            } elseif (isset($responseBody['code'])) {
                $message = (string) $responseBody['code'];
            }
        }

        return 'Failed (HTTP ' . $statusCode . '): ' . $message;
    }

    public static function parseFieldMapping(mixed $value): array
    {
        if (is_string($value)) {
            $decoded = json_decode($value, true);
            return is_array($decoded) ? $decoded : [];
        }

        return is_array($value) ? $value : [];
    }

    public static function parseIdList(mixed $value): array
    {
        if (is_string($value)) {
            $value = array_map('trim', explode(',', $value));
        }

        if (!is_array($value)) {
            return [];
        }

        $ids = [];
        foreach ($value as $item) {
            if ($item === '' || $item === null) {
                continue;
            }

            $id = (int) $item;
            if ($id > 0) {
                $ids[] = $id;
            }
        }

        return array_values(array_unique($ids));
    }

    public static function parseCsvList(mixed $value): array
    {
        if (is_string($value)) {
            $value = explode(',', $value);
        }

        if (!is_array($value)) {
            return [];
        }

        return array_values(array_filter(array_map('trim', $value), static function ($item): bool {
            return $item !== '';
        }));
    }

    public static function emailRecipients(mixed $value): array
    {
        return array_map(static function (string $email): array {
            return ['email' => $email];
        }, self::parseCsvList($value));
    }

    public static function limit(mixed $value, int $default = 50, int $max = 1000): int
    {
        $limit = is_numeric($value) ? (int) $value : $default;

        if ($limit < 1) {
            return $default;
        }

        return min($max, $limit);
    }

    public static function attributeCategory(mixed $value): string
    {
        $category = (string) $value;
        $allowed  = ['normal', 'transactional', 'category', 'calculated', 'global'];

        return in_array($category, $allowed, true) ? $category : 'normal';
    }

    public static function parseJsonObject(mixed $value): ?array
    {
        if (is_array($value)) {
            return $value;
        }

        if (!is_string($value) || trim($value) === '') {
            return [];
        }

        $decoded = json_decode($value, true);

        return is_array($decoded) ? $decoded : null;
    }
}
