import * as React from 'react';
import { renderToBuffer } from '@react-pdf/renderer';

import type { ProductData } from '../model/types';
import { buildDatasheetModel } from '../model/build-datasheet-model';
import { loadImageAsPngDataUrl, loadQrAsPngDataUrl } from './assets';
import { DatasheetDocument } from './DatasheetDocument';

export async function generateDatasheetPdfBuffer(args: {
  product: ProductData;
  locale: 'en' | 'de';
}): Promise<Buffer> {
  const model = buildDatasheetModel({ product: args.product, locale: args.locale });

  const logoDataUrl =
    (await loadImageAsPngDataUrl('/media/logo.svg')) ||
    (await loadImageAsPngDataUrl('/media/logo.webp')) ||
    null;

  const heroDataUrl = await loadImageAsPngDataUrl(model.product.heroSrc);
  const qrDataUrl = await loadQrAsPngDataUrl(model.product.productUrl);

  const element = <DatasheetDocument model={model} assets={{ logoDataUrl, heroDataUrl, qrDataUrl }} />;
  return await renderToBuffer(element);
}

