<?php

declare(strict_types=1);

namespace App\Services\Uploads;

use App\DTOs\Uploads\UploadScanResult;
use RuntimeException;
use Symfony\Component\Process\Process;

final class UploadScanService
{
    public function scan(string $path): UploadScanResult
    {
        if (! (bool) config('uploads.scan.enabled', false)) {
            return UploadScanResult::clean();
        }

        $command = config('uploads.scan.command', []);
        if (! is_array($command) || $command === []) {
            throw new RuntimeException('Upload scan enabled but no command configured.');
        }

        $command = $this->buildCommand($command, $path);
        $process = new Process($command);
        $process->run();

        if ($process->isSuccessful()) {
            return UploadScanResult::clean();
        }

        if ($process->getExitCode() === 1) {
            return UploadScanResult::infected(trim($process->getOutput()));
        }

        throw new RuntimeException('Upload scan failed: ' . trim($process->getErrorOutput()));
    }

    private function buildCommand(array $command, string $path): array
    {
        return array_map(static function (string $part) use ($path): string {
            return $part === '{path}' ? $path : $part;
        }, $command);
    }
}
