const path = require('path');

const allowedTypes = new Map([
  ['image/jpeg', new Set(['.jpg', '.jpeg'])],
  ['image/png', new Set(['.png'])],
  ['image/webp', new Set(['.webp'])],
  ['application/pdf', new Set(['.pdf'])],
  ['text/plain', new Set(['.txt'])],
]);

function contentMatches(mimeType, buffer) {
  if (mimeType === 'image/jpeg') {
    return buffer.length >= 3 && buffer[0] === 0xff && buffer[1] === 0xd8 && buffer[2] === 0xff;
  }
  if (mimeType === 'image/png') {
    return buffer.subarray(0, 8).equals(Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]));
  }
  if (mimeType === 'image/webp') {
    return buffer.subarray(0, 4).toString('ascii') === 'RIFF' && buffer.subarray(8, 12).toString('ascii') === 'WEBP';
  }
  if (mimeType === 'application/pdf') {
    return buffer.subarray(0, 5).toString('ascii') === '%PDF-';
  }
  if (mimeType === 'text/plain') {
    return !buffer.includes(0);
  }

  return false;
}

function validateFileUpload(file, filename) {
  const mimeType = String(file.mimetype || '').toLowerCase();
  const extension = path.extname(filename).toLowerCase();
  const extensions = allowedTypes.get(mimeType);

  if (!extensions || !extensions.has(extension) || !contentMatches(mimeType, file.buffer)) {
    const error = new Error('unsupported_file_type');
    error.code = 415;
    throw error;
  }
}

module.exports = { validateFileUpload };
