import { C as error, O as fail } from '../../../../chunks/utils.js-mIi_c4Oz.js';
import Papa from 'papaparse';
import { a as hasRole } from '../../../../chunks/auth.js-D502gejJ.js';
import { n as normalizeRole, m as importUsers } from '../../../../chunks/queries.js-BUUEc74j.js';

const load = async ({ locals }) => {
  if (!hasRole(locals.user, "admin")) throw error(403, "Solo administración.");
  return {};
};
function norm(h) {
  return h.normalize("NFD").replace(/[̀-ͯ]/g, "").trim().toLowerCase();
}
const HEADER_MAP = {
  nombre: "name",
  name: "name",
  "nombre completo": "name",
  email: "email",
  correo: "email",
  "correo electronico": "email",
  identificador: "identifier",
  dni: "identifier",
  "nº empleado": "identifier",
  "n empleado": "identifier",
  rol: "role",
  role: "role",
  perfil: "role"
};
const actions = {
  default: async ({ request, locals }) => {
    if (!hasRole(locals.user, "admin")) throw error(403, "Solo administración.");
    const csv = String((await request.formData()).get("csv") ?? "").trim();
    if (!csv) return fail(400, { error: "Pega o sube un CSV con al menos una fila." });
    const parsed = Papa.parse(csv, {
      header: true,
      skipEmptyLines: true,
      transformHeader: (h) => HEADER_MAP[norm(h)] ?? norm(h)
    });
    if (parsed.errors.length) {
      return fail(400, { error: `Error al leer el CSV: ${parsed.errors[0].message}` });
    }
    const rows = [];
    for (const r of parsed.data) {
      const name = (r.name ?? "").trim();
      if (!name) continue;
      rows.push({
        name,
        email: (r.email ?? "").trim().toLowerCase() || null,
        identifier: (r.identifier ?? "").trim() || null,
        role: normalizeRole(r.role ?? "consulta"),
        can_borrow: true,
        active: true
      });
    }
    if (rows.length === 0) {
      return fail(400, {
        error: 'No se encontró ninguna fila válida. Asegúrate de incluir una columna "nombre".'
      });
    }
    const result = importUsers(rows);
    return {
      success: `Importación completada: ${result.created} creados, ${result.updated} actualizados, ${result.skipped} omitidos.`
    };
  }
};

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

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