import { C as error, N as redirect, O as fail } from '../../../../chunks/utils.js-mIi_c4Oz.js';
import QRCode from 'qrcode';
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 { b as buildQrPayload } from '../../../../chunks/qr.js-BYghGLdS.js';
import { r as returnDevice, c as checkoutDevice, g as getDeviceView, b as listUsers, d as deviceHistory } from '../../../../chunks/queries.js-BUUEc74j.js';

const load = async ({ params }) => {
  const id = Number(params.id);
  const device = getDeviceView(id);
  if (!device) throw error(404, "Equipo no encontrado.");
  const qrSvg = await QRCode.toString(buildQrPayload(device.code, device.category_code), {
    type: "svg",
    margin: 1,
    errorCorrectionLevel: "M"
  });
  return {
    device,
    history: deviceHistory(id),
    borrowers: listUsers(true),
    qrSvg,
    defaultLoanDays: Number(getSetting("loan_default_days", "7"))
  };
};
const actions = {
  checkout: async ({ request, params, locals }) => {
    if (!hasRole(locals.user, "gestor")) throw error(403, "Sin permisos.");
    const id = Number(params.id);
    const form = await request.formData();
    const userIdRaw = String(form.get("user_id") ?? "").trim();
    const manualName = String(form.get("borrower_name") ?? "").trim();
    const dueRaw = String(form.get("due_at") ?? "").trim();
    const notes = String(form.get("notes") ?? "").trim();
    let userId = null;
    let borrowerName = manualName;
    if (userIdRaw) {
      userId = Number(userIdRaw);
      const u = db.prepare("SELECT name FROM users WHERE id = ?").get(userId);
      if (u) borrowerName = u.name;
    }
    if (!borrowerName) {
      return fail(400, { error: "Indica quién se lleva el equipo (usuario o nombre)." });
    }
    const dueAt = dueRaw ? `${dueRaw} 12:00:00` : null;
    const res = checkoutDevice({
      deviceId: id,
      userId,
      borrowerName,
      dueAt,
      operatorId: locals.user.id,
      notes
    });
    if (!res.ok) return fail(400, { error: res.error });
    return { success: "Préstamo registrado." };
  },
  return: async ({ params, locals }) => {
    if (!hasRole(locals.user, "gestor")) throw error(403, "Sin permisos.");
    const res = returnDevice(Number(params.id), locals.user.id);
    if (!res.ok) return fail(400, { error: res.error });
    return { success: "Devolución registrada." };
  },
  delete: async ({ params, locals }) => {
    if (!hasRole(locals.user, "admin")) throw error(403, "Solo administración puede eliminar.");
    db.prepare("DELETE FROM devices WHERE id = ?").run(Number(params.id));
    throw redirect(303, "/devices");
  }
};

var _page_server_ts = /*#__PURE__*/Object.freeze({
  __proto__: null,
  actions: actions,
  load: load
});

export { _page_server_ts as _ };
//# sourceMappingURL=_page.server.ts.js-DIvyeO0j.js.map
