const mimeToExtensionMap = {
    // Images
    "image/jpeg": "jpg",
    "image/png": "png",
    "image/gif": "gif",
    "image/webp": "webp",
    "image/svg+xml": "svg",
    "image/bmp": "bmp",
    "image/tiff": "tiff",
    "image/x-icon": "ico",

    // Videos
    "video/mp4": "mp4",
    "video/mpeg": "mpeg",
    "video/ogg": "ogv",
    "video/webm": "webm",
    "video/x-msvideo": "avi",
    "video/x-flv": "flv",
    "video/quicktime": "mov",

    // Audio
    "audio/mpeg": "mp3",
    "audio/ogg": "ogg",
    "audio/wav": "wav",
    "audio/webm": "weba",
    "audio/aac": "aac",
    "audio/flac": "flac",

    // Documents
    "application/pdf": "pdf",
    "application/zip": "zip",
    "application/json": "json",
    "application/javascript": "js",
    "application/xml": "xml",
    "application/vnd.ms-excel": "xls",
    "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet": "xlsx",
    "application/msword": "doc",
    "application/vnd.openxmlformats-officedocument.wordprocessingml.document": "docx",
    "application/vnd.ms-powerpoint": "ppt",
    "application/vnd.openxmlformats-officedocument.presentationml.presentation": "pptx",

    // Google Drive Document Formats
    "application/vnd.google-apps.document": "gdoc",
    "application/vnd.google-apps.spreadsheet": "gsheet",
    "application/vnd.google-apps.presentation": "gslides",
    "application/vnd.google-apps.form": "gform",
    "application/vnd.google-apps.drawing": "gdraw",
    "application/vnd.google-apps.script": "gscript",

    // Text and Code
    "text/plain": "txt",
    "text/csv": "csv",
    "text/html": "html",
    "text/css": "css",
    "text/javascript": "js",
    "text/markdown": "md"
};

/**
 * Get file extension from a MIME type.
 * @param {string} mimeType - The MIME type of the file.
 * @returns {string} - The file extension (without the dot) or an empty string if not found.
 */
export function getFileExtension(mimeType: string): string {
    if (!mimeType || typeof mimeType !== "string") {
        return "";
    }

    mimeType = mimeType.toLowerCase().trim();

    // Check predefined mapping
    if (mimeToExtensionMap[mimeType]) {
        return mimeToExtensionMap[mimeType];
    }

    // Try using `mime-types` package if available (Node.js)
    try {
        const mime = require("mime-types");
        const ext = mime.extension(mimeType);
        if (ext) return ext;
    } catch (error) {
        // Silent fail for browser compatibility
    }

    // Attempt to extract extension from MIME subtype (last part after '/')
    const parts = mimeType.split("/");
    if (parts.length === 2 && parts[1]) {
        return parts[1].split("+")[0]; // Removes "+xml" in cases like "application/atom+xml"
    }

    return "";
}  