<?php
namespace App\Services;

use Illuminate\Http\UploadedFile;
use Symfony\Component\Process\Process;

class FileSecurityService
{
    public function scan(UploadedFile $file): array
    {
        $contents=substr($file->get() ?: '',0,2 * 1024 * 1024);
        $extension=strtolower($file->getClientOriginalExtension());
        $name=strtolower($file->getClientOriginalName());
        $threats=[];
        if(str_contains($contents,'EICAR-STANDARD-ANTIVIRUS-TEST-FILE'))$threats[]='EICAR test signature';
        if(preg_match('/\.(php\d?|phtml|phar|cgi|pl|exe|bat|cmd|ps1)(\.|$)/i',$name))$threats[]='Executable or script extension';
        if(in_array($extension,['txt','csv'],true) && preg_match('/<\?(php|=)|<script\b|powershell\s+-/i',$contents))$threats[]='Active script content';
        $engine='application-signatures';$binary=config('file_security.clamav_binary');
        if($binary && $threats===[]){
            try{$process=new Process([$binary,'--no-summary',$file->getPathname()]);$process->setTimeout(config('file_security.clamav_timeout',30));$process->run();$engine='clamav';
                if($process->getExitCode()===1)$threats[]='ClamAV: '.trim($process->getOutput().$process->getErrorOutput());
                elseif(!$process->isSuccessful())throw new \RuntimeException(trim($process->getErrorOutput())?:'ClamAV scan failed.');
            }catch(\Throwable $e){if(config('file_security.fail_closed',true))$threats[]='Scanner unavailable: '.$e->getMessage();else $engine='application-signatures (ClamAV unavailable)';}
        }
        return ['clean'=>$threats===[],'status'=>$threats===[]?'clean':'quarantined','details'=>$threats?implode('; ',$threats):ucfirst($engine).' scan passed','engine'=>$engine];
    }
}
