import { C as error } from '../../../../chunks/utils.js-mIi_c4Oz.js';
import { a as hasRole } from '../../../../chunks/auth.js-D502gejJ.js';
import { d as db, g as getSetting } from '../../../../chunks/db.js-le-jjQPv.js';
import { PDFDocument, StandardFonts, rgb } from 'pdf-lib';
import QRCode from 'qrcode';
import { b as buildQrPayload } from '../../../../chunks/qr.js-BYghGLdS.js';
import { g as getPreset, l as labelsPerSheet } from '../../../../chunks/labels-presets.js-DFpXmbAX.js';
import '../../../../chunks/utils2.js-BQzn9ikS.js';
import 'node:crypto';
import 'node:sqlite';
import 'node:fs';
import 'node:path';
import 'node:os';

const MM = 72 / 25.4;
async function qrPng(payload) {
  return QRCode.toDataURL(payload, { margin: 0, width: 512, errorCorrectionLevel: "M" });
}
function fitFontSize(font, text, maxWidthPt, start, min = 6) {
  let size = start;
  while (size > min && font.widthOfTextAtSize(text, size) > maxWidthPt) size -= 0.5;
  return size;
}
async function generateLabelsPdf(items, opts) {
  const preset = getPreset(opts.presetKey);
  const perSheet = labelsPerSheet(preset);
  const offX = (opts.offsetXmm ?? 0) * MM;
  const offY = (opts.offsetYmm ?? 0) * MM;
  const pdf = await PDFDocument.create();
  const fontBold = await pdf.embedFont(StandardFonts.HelveticaBold);
  const fontReg = await pdf.embedFont(StandardFonts.Helvetica);
  const qrCache = /* @__PURE__ */ new Map();
  async function embedQr(payload) {
    let img = qrCache.get(payload);
    if (!img) {
      img = await pdf.embedPng(await qrPng(payload));
      qrCache.set(payload, img);
    }
    return img;
  }
  const pageWpt = preset.pageW * MM;
  const pageHpt = preset.pageH * MM;
  const labelWpt = preset.labelW * MM;
  const labelHpt = preset.labelH * MM;
  const pad = 2.5 * MM;
  let page = pdf.addPage([pageWpt, pageHpt]);
  let cell = opts.startIndex ?? 0;
  for (const item of items) {
    if (cell >= perSheet) {
      page = pdf.addPage([pageWpt, pageHpt]);
      cell = 0;
    }
    const col = cell % preset.cols;
    const row = Math.floor(cell / preset.cols);
    const x = (preset.marginLeft + col * (preset.labelW + preset.gutterX)) * MM + offX;
    const yTop = (preset.marginTop + row * (preset.labelH + preset.gutterY)) * MM - offY;
    const y = pageHpt - yTop - labelHpt;
    if (opts.showBorder) {
      page.drawRectangle({
        x,
        y,
        width: labelWpt,
        height: labelHpt,
        borderColor: rgb(0.85, 0.85, 0.85),
        borderWidth: 0.5
      });
    }
    const qrSize = labelHpt - 2 * pad;
    const img = await embedQr(buildQrPayload(item.code, item.categoryCode));
    page.drawImage(img, { x: x + pad, y: y + pad, width: qrSize, height: qrSize });
    const textX = x + pad + qrSize + pad;
    const textW = x + labelWpt - pad - textX;
    const codeSize = fitFontSize(fontBold, item.code, textW, 18);
    const codeY = y + labelHpt - pad - codeSize;
    page.drawText(item.code, { x: textX, y: codeY, size: codeSize, font: fontBold, color: rgb(0.06, 0.09, 0.16) });
    if (item.categoryName) {
      const catSize = fitFontSize(fontReg, item.categoryName, textW, 10);
      page.drawText(item.categoryName, {
        x: textX,
        y: codeY - catSize - 3,
        size: catSize,
        font: fontReg,
        color: rgb(0.28, 0.33, 0.4)
      });
    }
    if (opts.centerName) {
      const cSize = fitFontSize(fontReg, opts.centerName, textW, 8, 5);
      page.drawText(opts.centerName, {
        x: textX,
        y: y + pad,
        size: cSize,
        font: fontReg,
        color: rgb(0.55, 0.6, 0.66)
      });
    }
    cell++;
  }
  return pdf.save();
}
const POST = async ({ request, locals }) => {
  if (!hasRole(locals.user, "gestor")) throw error(403, "Sin permisos.");
  const form = await request.formData();
  const preset = String(form.get("preset") ?? "apli1274");
  const offsetX = Number(form.get("offset_x") ?? 0) || 0;
  const offsetY = Number(form.get("offset_y") ?? 0) || 0;
  const startIndex = Math.max(0, Number(form.get("start_index") ?? 0) || 0);
  const showBorder = form.get("border") === "on";
  const includeCenter = form.get("center") === "on";
  const ids = form.getAll("id").map((v) => Number(v)).filter((n) => Number.isFinite(n));
  if (ids.length === 0) throw error(400, "No se han seleccionado equipos.");
  const placeholders = ids.map(() => "?").join(",");
  const rows = db.prepare(
    `SELECT d.code, c.name AS category_name, c.code AS category_code
			 FROM devices d LEFT JOIN categories c ON c.id = d.category_id
			 WHERE d.id IN (${placeholders})
			 ORDER BY d.code`
  ).all(...ids);
  const items = rows.map((r) => ({
    code: r.code,
    categoryName: r.category_name,
    categoryCode: r.category_code
  }));
  const pdfBytes = await generateLabelsPdf(items, {
    presetKey: preset,
    offsetXmm: offsetX,
    offsetYmm: offsetY,
    startIndex,
    showBorder,
    centerName: includeCenter ? getSetting("center_name", "") : void 0
  });
  return new Response(pdfBytes, {
    headers: {
      "Content-Type": "application/pdf",
      "Content-Disposition": `inline; filename="etiquetas-${preset}.pdf"`
    }
  });
};

export { POST };
//# sourceMappingURL=_server.ts.js-DrKY3bkr.js.map
