import { scryptSync, timingSafeEqual, randomBytes } from 'node:crypto';
import { d as db } from './db.js-le-jjQPv.js';

const SESSION_COOKIE = "edumind_session";
const SESSION_DAYS = 30;
function hashPassword(password) {
  const salt = randomBytes(16);
  const derived = scryptSync(password, salt, 64);
  return `scrypt$${salt.toString("hex")}$${derived.toString("hex")}`;
}
function verifyPassword(password, stored) {
  if (!stored) return false;
  const [scheme, saltHex, hashHex] = stored.split("$");
  if (scheme !== "scrypt" || !saltHex || !hashHex) return false;
  const salt = Buffer.from(saltHex, "hex");
  const expected = Buffer.from(hashHex, "hex");
  const derived = scryptSync(password, salt, expected.length);
  return derived.length === expected.length && timingSafeEqual(derived, expected);
}
function createSession(userId, cookies) {
  const token = randomBytes(32).toString("hex");
  const expires = new Date(Date.now() + SESSION_DAYS * 864e5);
  db.prepare(
    "INSERT INTO sessions (token, user_id, expires_at) VALUES (?, ?, datetime(?, 'unixepoch'))"
  ).run(token, userId, Math.floor(expires.getTime() / 1e3));
  cookies.set(SESSION_COOKIE, token, {
    path: "/",
    httpOnly: true,
    sameSite: "lax",
    // En modo red (HTTPS) la cookie es 'secure'; en modo local (HTTP) no,
    // para que funcione sin certificado. Se deriva del esquema de ORIGIN.
    secure: (process.env.ORIGIN ?? "").startsWith("https"),
    expires
  });
}
function destroySession(cookies) {
  const token = cookies.get(SESSION_COOKIE);
  if (token) db.prepare("DELETE FROM sessions WHERE token = ?").run(token);
  cookies.delete(SESSION_COOKIE, { path: "/" });
}
function getSessionUser(cookies) {
  const token = cookies.get(SESSION_COOKIE);
  if (!token) return null;
  const row = db.prepare(
    `SELECT u.id, u.name, u.email, u.role
			 FROM sessions s JOIN users u ON u.id = s.user_id
			 WHERE s.token = ? AND s.expires_at > datetime('now') AND u.active = 1`
  ).get(token);
  return row ?? null;
}
function pruneSessions() {
  db.prepare("DELETE FROM sessions WHERE expires_at <= datetime('now')").run();
}
const RANK = { consulta: 0, gestor: 1, admin: 2 };
function hasRole(user, min) {
  if (!user) return false;
  return RANK[user.role] >= RANK[min];
}
function hasAnyAdmin() {
  const row = db.prepare(
    "SELECT COUNT(*) AS n FROM users WHERE role = 'admin' AND password_hash IS NOT NULL AND active = 1"
  ).get();
  return row.n > 0;
}

export { hasRole as a, hashPassword as b, createSession as c, destroySession as d, getSessionUser as g, hasAnyAdmin as h, pruneSessions as p, verifyPassword as v };
//# sourceMappingURL=auth.js-D502gejJ.js.map
