<?php

declare(strict_types=1);

namespace Apexl\Io\Logger\Services\HandlerCreator;

use Apexl\Io\Factories\MailerFactory;
use Apexl\Io\Logger\Dtos\HandlerConfig;
use Apexl\Io\Logger\Dtos\HandlerConfigParams\MailHandlerConfigParams;
use Apexl\Io\Logger\Dtos\StreamConfig;
use Apexl\Io\Logger\Handlers\IoMailerHandler;
use Monolog\Handler\BufferHandler;
use Monolog\Handler\HandlerInterface;
use Monolog\Handler\NullHandler;

final readonly class MailLogHandlerCreator extends HandlerCreator
{
    public function __construct(private MailerFactory $mailerFactory) {}

    public function create(
        string $streamName,
        HandlerConfig $handlerConfig,
        StreamConfig $streamConfig
    ): HandlerInterface {
        /** @var MailHandlerConfigParams $params */
        $params = $handlerConfig->params;
        $level = $this->level($handlerConfig, $streamConfig);

        if (!$params->to) {
            error_log(
                sprintf(
                    'The \'mail\' log handler on stream \'%s\' has no `to` address; not sending',
                    $streamName
                )
            );

            return new NullHandler();
        }

        $handler = new IoMailerHandler(
            $this->mailerFactory,
            $params->to,
            $params->subject ?? sprintf('%s log: %s and above', $streamName, $level),
            $level,
        );

        // Buffer so a run producing many records sends one email, not one per record.
        return new BufferHandler($handler, $params->max_records, $level);
    }
}
