<?php
/**
 * 2026 Paysera
 *
 * NOTICE OF LICENSE
 *
 * This source file is subject to the Academic Free License (AFL 3.0)
 * that is bundled with this package in the file LICENSE.txt.
 * It is also available through the world-wide-web at this URL:
 * http://opensource.org/licenses/afl-3.0.php
 * If you did not receive a copy of the license and are unable to
 * obtain it through the world-wide-web, please send an email
 * to license@prestashop.com so we can send you a copy immediately.
 *
 * @author Paysera <plugins@paysera.com>
 * @copyright 2026 Paysera
 * @license http://opensource.org/licenses/afl-3.0.php Academic Free License (AFL 3.0)
 * International Registered Trademark & Property of Paysera
 */

declare(strict_types=1);

namespace Paysera\PrestashopPayments\Logger;

use Psr\Log\AbstractLogger;
use Psr\Log\InvalidArgumentException;
use Psr\Log\LogLevel;

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

class PayseraLogger extends AbstractLogger
{
    public const MODULE_NAME = 'PayseraPayments';

    public function log($level, $message, array $context = []): void
    {
        $severity = $this->mapLogLevelToSeverity($level);
        $formattedMessage = $this->formatMessage($message, $context);

        \PrestaShopLogger::addLog(
            $formattedMessage,
            $severity,
            null,
            self::MODULE_NAME,
            $context['id'] ?? null,
            true
        );
    }

    private function mapLogLevelToSeverity(string $level): int
    {
        return match ($level) {
            LogLevel::EMERGENCY,
            LogLevel::ALERT,
            LogLevel::CRITICAL => 4,
            LogLevel::ERROR => 3,
            LogLevel::WARNING => 2,
            LogLevel::NOTICE,
            LogLevel::INFO,
            LogLevel::DEBUG => 1,
            default => throw new InvalidArgumentException(sprintf('Unknown PSR-3 log level "%s"', $level)),
        };
    }

    private function formatMessage(string $message, array $context): string
    {
        if ($context === []) {
            return $message;
        }

        return sprintf('%s %s', $message, json_encode($context));
    }
}
