import * as pdfjsLib from '../../../pdfjs/pdf.min.js';
import { browser } from 'wxt/browser';

pdfjsLib.GlobalWorkerOptions.workerSrc = browser.runtime.getURL('pdfjs/pdf.worker.min.js');

const ensureUint8Array = (buffer) => {
  if (buffer instanceof Uint8Array) {
    return buffer;
  }

  return new Uint8Array(buffer);
};

export const parsePdfBufferToText = async (pdfBuffer) => {
  const pdfData = ensureUint8Array(pdfBuffer);
  const loadingTask = pdfjsLib.getDocument({
    data: pdfData,
    disableWorker: true,
  });

  const pdfDocument = await loadingTask.promise;
  const textPages = [];

  for (let pageNum = 1; pageNum <= pdfDocument.numPages; pageNum++) {
    const page = await pdfDocument.getPage(pageNum);
    const textContent = await page.getTextContent();
    const pageText = textContent.items.map((item) => item.str).join(' ');

    textPages.push(pageText);
  }

  return textPages.join('\n\n');
};
