// ESM wrapper for mime-types to fix CJS interop in vite build
// @blocklet/uploader uses _mimeTypes.default.lookup() pattern
import mimeDb from 'mime-db';

const types: Record<string, string> = {};
const extensions: Record<string, string[]> = {};

// Build lookup tables from mime-db
Object.entries(mimeDb).forEach(([type, data]: [string, any]) => {
  if (data.extensions) {
    data.extensions.forEach((ext: string) => {
      types[ext] = type;
    });
    extensions[type] = data.extensions;
  }
});

export function lookup(filenameOrExt: string): string | false {
  if (!filenameOrExt || typeof filenameOrExt !== 'string') return false;
  const ext = filenameOrExt.replace(/^.*\./, '').toLowerCase();
  return types[ext] || false;
}

export function extension(type: string): string | false {
  if (!type || typeof type !== 'string') return false;
  const mime = type.split(';')[0].trim().toLowerCase();
  const exts = extensions[mime];
  return exts && exts.length > 0 ? exts[0] : false;
}

export function contentType(str: string): string | false {
  const mime = str.indexOf('/') === -1 ? lookup(str) : str;
  return mime || false;
}

export function charset(type: string): string | false {
  const mime = typeof type === 'string' && type.split(';')[0].trim().toLowerCase();
  if (mime && /^text\/|^application\/(javascript|json|xml|ecmascript)/.test(mime)) {
    return 'UTF-8';
  }
  return false;
}

export const charsets = { lookup: charset };

export default { lookup, extension, contentType, charset, charsets };
