/**
 * Detect image MIME type from a buffer using magic numbers and SVG heuristic.
 * Returns a Content-Type string suitable for res.set('Content-Type', ...).
 * Fallback: application/octet-stream.
 *
 * Supports: PNG, JPEG, GIF, WebP, SVG.
 */
export function getImageContentType(buffer) {
    if (!buffer || !Buffer.isBuffer(buffer) || buffer.length === 0) {
        return 'application/octet-stream';
    }

    const b = buffer;

    // PNG: 89 50 4E 47 0D 0A 1A 0A
    if (b.length >= 8 && b[0] === 0x89 && b[1] === 0x50 && b[2] === 0x4E && b[3] === 0x47 && b[4] === 0x0D && b[5] === 0x0A && b[6] === 0x1A && b[7] === 0x0A) {
        return 'image/png';
    }

    // JPEG: FF D8 FF
    if (b.length >= 3 && b[0] === 0xFF && b[1] === 0xD8 && b[2] === 0xFF) {
        return 'image/jpeg';
    }

    // GIF: GIF87a or GIF89a
    if (b.length >= 6 && b[0] === 0x47 && b[1] === 0x49 && b[2] === 0x46 && b[3] === 0x38 && (b[4] === 0x37 || b[4] === 0x39) && b[5] === 0x61) {
        return 'image/gif';
    }

    // WebP: RIFF....WEBP
    if (b.length >= 12 && b[0] === 0x52 && b[1] === 0x49 && b[2] === 0x46 && b[3] === 0x46 && b[8] === 0x57 && b[9] === 0x45 && b[10] === 0x42 && b[11] === 0x50) {
        return 'image/webp';
    }

    // SVG: text-based, check for <?xml or <svg (optional BOM/whitespace)
    try {
        const start = (b[0] === 0xEF && b[1] === 0xBB && b[2] === 0xBF) ? b.subarray(3) : b;
        const head = start.toString('utf8', 0, Math.min(200, start.length)).trim();
        if (/^\s*(<\?xml|<svg)/i.test(head)) {
            return 'image/svg+xml';
        }
    } catch {
        // invalid UTF-8, not SVG
    }

    return 'application/octet-stream';
}
