"use strict";
const crypto = require("crypto");
const bcrypt = require("bcryptjs");

const sessions = new Map();

function createSession(data) {
  const token = crypto.randomBytes(32).toString("hex");
  sessions.set(token, { ...data, _ts: Date.now() });
  return token;
}

function destroySession(token) {
  if (token) sessions.delete(token);
}

function getSession(req) {
  const token = req.cookies?.scholar_sid;
  if (!token) return null;
  const s = sessions.get(token);
  if (!s) return null;
  // 7-day expiry
  if (Date.now() - s._ts > 7 * 24 * 60 * 60 * 1000) {
    sessions.delete(token);
    return null;
  }
  return s;
}

function getSessionToken(req) {
  return req.cookies?.scholar_sid;
}

function hashPassword(password) {
  return crypto.createHash("sha256").update(password).digest("hex");
}

function verifyPassword(password, hash) {
  // Support both SHA256 (legacy) and bcrypt
  if (hash.startsWith("$2") ) {
    return bcrypt.compareSync(password, hash);
  }
  return hashPassword(password) === hash;
}

const COOKIE = "scholar_sid";
const COOKIE_OPTS = {
  httpOnly: true,
  sameSite: "lax",
  path: "/",
  maxAge: 60 * 60 * 24 * 7 * 1000,
};

module.exports = {
  createSession, destroySession, getSession, getSessionToken,
  hashPassword, verifyPassword, COOKIE, COOKIE_OPTS,
};
