import { downloadContentFromMessage } from '@whiskeysockets/baileys';
import { createRequire } from 'module';

const require  = createRequire(import.meta.url);
const mammoth  = require('mammoth');

export const MIME_EXT = {
  'application/pdf': 'pdf',
  'application/msword': 'doc',
  'application/vnd.openxmlformats-officedocument.wordprocessingml.document': 'docx',
};

export function getDocMsg(msg) {
  return (
    msg.message?.documentMessage ||
    msg.message?.documentWithCaptionMessage?.message?.documentMessage ||
    null
  );
}

export async function downloadDocument(docMsg) {
  const stream = await downloadContentFromMessage(docMsg, 'document');
  let buffer = Buffer.alloc(0);
  for await (const chunk of stream) buffer = Buffer.concat([buffer, chunk]);
  const mime = docMsg.mimetype || 'application/octet-stream';
  const ext  = MIME_EXT[mime] || 'bin';
  return { buffer, mime, ext };
}

export async function extractText(buffer, ext) {
  try {
    if (ext === 'pdf') {
      const { PDFParse } = await import('pdf-parse');
      const parser = new PDFParse({ data: buffer });
      const result = await parser.getText();
      return (result.text || '').trim();
    }
    if (ext === 'docx' || ext === 'doc') {
      const result = await mammoth.extractRawText({ buffer });
      return (result.value || '').trim();
    }
  } catch (e) {
    console.error('[extractText]', e.message);
  }
  return '';
}
