'use strict';
/* ── Magic bytes validation (shared between file and submission uploads) ── */
const fs = require('fs');

const MAGIC = [
  { mime: 'application/pdf',  bytes: [0x25,0x50,0x44,0x46],                     offset: 0 }, // %PDF
  { mime: 'image/png',        bytes: [0x89,0x50,0x4E,0x47,0x0D,0x0A,0x1A,0x0A], offset: 0 },
  { mime: 'image/jpeg',       bytes: [0xFF,0xD8,0xFF],                           offset: 0 },
  { mime: 'image/gif',        bytes: [0x47,0x49,0x46,0x38],                      offset: 0 }, // GIF8
  { mime: 'image/webp',       bytes: [0x57,0x45,0x42,0x50],                      offset: 8 }, // RIFF????WEBP
  // OLE2 (doc, xls, ppt)
  { mime: 'application/msword',       bytes: [0xD0,0xCF,0x11,0xE0], offset: 0 },
  { mime: 'application/vnd.ms-excel', bytes: [0xD0,0xCF,0x11,0xE0], offset: 0 },
  { mime: 'application/vnd.ms-powerpoint', bytes: [0xD0,0xCF,0x11,0xE0], offset: 0 },
  // ZIP/OOXML (docx, xlsx, pptx)
  { mime: 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',   bytes: [0x50,0x4B,0x03,0x04], offset: 0 },
  { mime: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',         bytes: [0x50,0x4B,0x03,0x04], offset: 0 },
  { mime: 'application/vnd.openxmlformats-officedocument.presentationml.presentation', bytes: [0x50,0x4B,0x03,0x04], offset: 0 },
];

function checkMagicBytes(filePath, declaredMime) {
  if (declaredMime === 'text/plain') return true; // txt has no magic bytes
  const rules = MAGIC.filter(m => m.mime === declaredMime);
  if (!rules.length) return false; // unknown mime → reject
  try {
    const needed = Math.max(...rules.map(r => r.offset + r.bytes.length));
    const buf  = Buffer.alloc(needed);
    const fd   = fs.openSync(filePath, 'r');
    const read = fs.readSync(fd, buf, 0, needed, 0);
    fs.closeSync(fd);
    if (read < needed) return false;
    return rules.some(r => r.bytes.every((b, i) => buf[r.offset + i] === b));
  } catch {
    return false;
  }
}

module.exports = { checkMagicBytes };
