<?php

/**
 * JCH Optimize - Performs several front-end optimizations for fast downloads.
 *
 * @author    Samuel Marshall <samuel@jch-optimize.net>
 * @copyright Copyright (c) 2022 Samuel Marshall / JCH Optimize
 * @license   GNU/GPLv3, or later. See LICENSE file
 *
 *  If LICENSE file missing, see <http://www.gnu.org/licenses/>.
 */

namespace JchOptimize\Log;

use Joomla\CMS\Log\Log;
use Psr\Log\AbstractLogger;
use Psr\Log\LogLevel;
use Stringable;

\defined('_JEXEC') or exit('Restricted Access');

/**
 * @psalm-suppress all
 */
class DelegatingPsrLoggerExtended extends AbstractLogger
{
    /**
     * @var Log
     */
    protected $logger;

    /**
     * @var array<string, int>
     */
    protected $priorityMap = [
        LogLevel::EMERGENCY => Log::EMERGENCY,
        LogLevel::ALERT     => Log::ALERT,
        LogLevel::CRITICAL  => Log::CRITICAL,
        LogLevel::ERROR     => Log::ERROR,
        LogLevel::WARNING   => Log::WARNING,
        LogLevel::NOTICE    => Log::NOTICE,
        LogLevel::INFO      => Log::INFO,
        LogLevel::DEBUG     => Log::DEBUG,
    ];

    public function __construct(Log $logger)
    {
        $this->logger = $logger;
    }

    public function log($level, string|Stringable $message, array $context = []): void
    {
        if (!\array_key_exists($level, $this->priorityMap)) {
            throw new \InvalidArgumentException('An invalid log level has been given.');
        }

        $priority = $this->priorityMap[$level];
        $context  = \array_merge($context, ['category' => 'com_jchoptimize']);

        $category = null;
        $date     = null;

        if (!empty($context['category'])) {
            $category = $context['category'];
        }

        if (!empty($context['date'])) {
            $date = $context['date'];
        }

        $this->logger::add((string) $message, $priority, $category, $date, $context);
    }
}
