<?php

declare(strict_types=1);

namespace App\Domain\Antivirus\Services;

use App\Domain\Antivirus\Adapters\ClamAvAdapter;
use App\Domain\Antivirus\Adapters\NoneAntivirusAdapter;
use App\Domain\Antivirus\Contracts\AntivirusAdapter;
use App\Domain\Sysapi\Contracts\SysapiBridge;

class AntivirusFactory
{
    public function __construct(private readonly SysapiBridge $sysapi) {}

    public function make(?string $driver = null): AntivirusAdapter
    {
        $driver = $driver ?? config('antivirus.driver', 'auto');

        return match ($driver) {
            'clamav' => new ClamAvAdapter($this->sysapi),
            'none', 'disabled' => new NoneAntivirusAdapter(),
            default => $this->autoDetect(),
        };
    }

    private function autoDetect(): AntivirusAdapter
    {
        $clamav = new ClamAvAdapter($this->sysapi);
        if ($clamav->isInstalled()) {
            return $clamav;
        }

        return new NoneAntivirusAdapter();
    }

    /**
     * @return array<int, array{driver: string, name: string, installed: bool, running: bool, version: string|null}>
     */
    public function listAll(): array
    {
        $adapters = [
            'clamav' => new ClamAvAdapter($this->sysapi),
            'none' => new NoneAntivirusAdapter(),
        ];

        $result = [];
        foreach ($adapters as $driver => $adapter) {
            $installed = $adapter->isInstalled();
            $result[] = [
                'driver' => $driver,
                'name' => $adapter->name(),
                'installed' => $installed,
                'running' => $installed && $adapter->isRunning(),
                'version' => $installed ? $adapter->version() : null,
            ];
        }

        return $result;
    }
}
