const { execFile } = require('child_process');
const fs = require('fs/promises');
const os = require('os');
const path = require('path');
const { promisify } = require('util');
const crypto = require('crypto');

const execFileAsync = promisify(execFile);

async function scanFile(filePath) {
  try {
    await execFileAsync('clamscan', ['--no-summary', filePath]);
  } catch (error) {
    console.error('Malware scan failed', { code: error.code, signal: error.signal });
    throw new Error('file_scan_failed');
  }
}

async function scanBuffer(buffer) {
  const scanPath = path.join(os.tmpdir(), `coaching-upload-${crypto.randomUUID()}`);
  await fs.writeFile(scanPath, buffer, { mode: 0o600 });

  try {
    await scanFile(scanPath);
  } finally {
    await fs.unlink(scanPath);
  }
}

module.exports = { scanBuffer, scanFile };
