<?php

namespace Velis\Filesystem\Av;

use Phalcon\Di\DiInterface;
use Phalcon\Di\ServiceProviderInterface;
use RuntimeException;
use Velis\App;
use Velis\Filesystem\Av\Concrete\ClamAvClient;
use Velis\Filesystem\Av\Concrete\Connection;
use Velis\Filesystem\Av\Concrete\FileHandler;
use Velis\Filesystem\Av\Contract\AvClientInterface;

/**
 * @author Szymon Janaczek <szymon.janaczek@velistech.com>
 */
final class AvServiceProvider implements ServiceProviderInterface
{
    public function register(DiInterface $di): void
    {
        if (!App::$config->av->enabled) {
            $di->set(AvClientInterface::class, fn () => null);
            return;
        }

        // AV is enabled, check whether the necessary configuration is set
        $allowedSourcePath = App::$config->av->clamAv->allowedSourcePath;
        $host = App::$config->av->clamAv->host;

        if ($allowedSourcePath === null) {
            throw new RuntimeException('ClamAV allowed source path is not set.');
        }

        if ($host === null) {
            throw new RuntimeException('ClamAV host is not set.');
        }

        $di->set(
            AvClientInterface::class,
            fn (): ClamAvClient => new ClamAvClient(
                connection: new Connection(
                    host: $host,
                    port: (int) (App::$config->av->clamAv->port ?? 3310),
                ),
                fileHandler: new FileHandler(
                    allowedSourcePath: $allowedSourcePath,
                ),
                maxResponseSize: (int) (App::$config->av->clamAv->maxResponseSize ?? 20000),
            )
        );
    }
}
