/**
 * Validates that the actual bytes of a base64-encoded image match its declared MIME type.
 * This prevents attackers from uploading malicious files with a spoofed extension/MIME.
 */

interface MagicSignature {
  mimeType: string;
  bytes: number[];
}

const SIGNATURES: MagicSignature[] = [
  { mimeType: "image/png", bytes: [0x89, 0x50, 0x4e, 0x47] }, // .PNG
  { mimeType: "image/jpeg", bytes: [0xff, 0xd8, 0xff] },
  { mimeType: "image/webp", bytes: [0x52, 0x49, 0x46, 0x46] }, // RIFF (WebP starts with RIFF....WEBP)
  { mimeType: "image/gif", bytes: [0x47, 0x49, 0x46, 0x38] }, // GIF8
  { mimeType: "image/bmp", bytes: [0x42, 0x4d] }, // BM
  { mimeType: "image/tiff", bytes: [0x49, 0x49, 0x2a, 0x00] }, // Little-endian TIFF
  { mimeType: "image/tiff", bytes: [0x4d, 0x4d, 0x00, 0x2a] }, // Big-endian TIFF
];

/**
 * Detects the actual MIME type of a binary buffer by checking magic bytes.
 * Returns null if no known image signature matches.
 */
export function detectImageMime(buffer: Uint8Array): string | null {
  for (const sig of SIGNATURES) {
    if (buffer.length >= sig.bytes.length && sig.bytes.every((b, i) => buffer[i] === b)) {
      // Extra check for WebP: bytes 8-11 must be "WEBP"
      if (sig.mimeType === "image/webp") {
        if (buffer.length < 12) continue;
        const webpTag = String.fromCharCode(buffer[8]!, buffer[9]!, buffer[10]!, buffer[11]!);
        if (webpTag !== "WEBP") continue;
      }
      return sig.mimeType;
    }
  }
  return null;
}

/**
 * Validates a data URL by comparing its declared MIME type against the actual magic bytes.
 * Returns { valid: true } or { valid: false, reason: string }.
 */
export function validateImageDataUrl(dataUrl: string): { valid: true } | { valid: false; reason: string } {
  // Parse the data URL
  const match = dataUrl.match(/^data:(image\/[a-z+]+);base64,(.+)$/i);
  if (!match) {
    return { valid: false, reason: "Not a valid base64 image data URL." };
  }

  const declaredMime = match[1]!.toLowerCase();
  const base64 = match[2]!;

  // Decode at least the first 16 bytes for signature checking
  let buffer: Uint8Array;
  try {
    const chunk = base64.slice(0, 24); // 24 base64 chars = 18 bytes, more than enough
    buffer = Uint8Array.from(atob(chunk), (c) => c.charCodeAt(0));
  } catch {
    return { valid: false, reason: "Invalid base64 encoding." };
  }

  const actualMime = detectImageMime(buffer);
  if (!actualMime) {
    return { valid: false, reason: "File content does not match any known image format." };
  }

  // Allow JPEG variants (image/jpeg matches image/jpg header)
  const normalize = (m: string) => m.replace("image/jpg", "image/jpeg");
  if (normalize(declaredMime) !== normalize(actualMime)) {
    return {
      valid: false,
      reason: `MIME type mismatch: declared "${declaredMime}" but actual content is "${actualMime}".`,
    };
  }

  return { valid: true };
}
