<?php

namespace Velis\Log;

use DateTimeZone;
use Phalcon\Di\DiInterface;
use Phalcon\Di\ServiceProviderInterface;
use Velis\App;
use Velis\Log\Sentry\BreadcrumbHelper;
use Velis\Log\Sentry\ScopeConfiguration;
use Velis\Timezone;

use function Sentry\init as sentryInit;

class LoggerServiceProvider implements ServiceProviderInterface
{
    public function register(DiInterface $di): void
    {
        sentryInit([
            'dsn' => App::$config->sentry->dsn,
            'environment' => App::getAppName() . '_' . App::getAppEnv(),
        ]);

        $di->set(
            name: LoggerFactory::class,
            definition: function () {
                $velisTimezone = Timezone::getDefaultTimezone();
                $timezone = new DateTimeZone($velisTimezone->getName());

                return new LoggerFactory($timezone);
            },
            shared: true,
        );

        $di->set(
            name: LoggerInterface::class,
            definition: function () use ($di) {
                $loggerFactory = $di->get(LoggerFactory::class);

                $logPath = implode(DIRECTORY_SEPARATOR, [
                    DATA_PATH,
                    'log',
                    'php',
                    'app_' . date('Y-m-d') . '.log',
                ]);

                $param = new LoggerFactoryParam(
                    channelName: 'app',
                    stream: $logPath,
                );

                return $loggerFactory->createLogger($param);
            },
            shared: true,
        );

        $di->set(
            name: 'logger.dbException',
            definition: function () {
                /** @var LoggerFactory $loggerFactory */
                $loggerFactory = App::getService(LoggerFactory::class);

                $logPath = App::$config->log->dbErrorsPath;
                $logPath = $logPath ? ROOT_PATH . $logPath : LOG_PATH . 'db';
                $logfile = $logPath . DIRECTORY_SEPARATOR . 'db_errors_' . date('Y-m') . '.log';

                $param = new LoggerFactoryParam(channelName: 'db', stream: $logfile);

                return $loggerFactory->createLogger($param);
            },
            shared: true,
        );

        $di->set(
            name: 'logger.xss',
            definition: function () {
                /** @var LoggerFactory $loggerFactory */
                $loggerFactory = App::getService(LoggerFactory::class);
                $logfile = LOG_PATH . 'php/xss.log';
                $param = new LoggerFactoryParam(channelName: 'xss', stream: $logfile);

                return $loggerFactory->createLogger($param);
            },
            shared: true,
        );

        $di->set(
            name: BreadcrumbHelper::class,
            definition: BreadcrumbHelper::class,
            shared: true,
        );

        $di->set(ScopeConfiguration::class, ScopeConfiguration::class, true);
    }
}
