/**
 * PDF conversion utilities with optional post-render resizing via sharp.
 */
import { pdfToImg } from "./pdfToImg.js";

function resolveDefault(module) {
  return module?.default ?? module;
}

export async function convertPDFToImage(pdfInput, options = {}) {
  const sharpModule = await import("sharp");
  const sharp = resolveDefault(sharpModule);

  const { width, height, page_numbers, scale = 2, ...pdfOnlyOptions } =
    options;

  const images = await pdfToImg(pdfInput, {
    page_numbers,
    scale,
    password: pdfOnlyOptions.password,
    docInitParams: pdfOnlyOptions.docInitParams,
  });

  if (!width && !height) {
    return images;
  }

  const resizeOptions = {};
  if (width) resizeOptions.width = width;
  if (height) resizeOptions.height = height;

  return Promise.all(
    images.map((image) => sharp(image).resize(resizeOptions).toBuffer()),
  );
}
