import crypto from "crypto";

export const SESSION_COOKIE = "midhub_crm_session";
const SESSION_TTL_MS = 12 * 60 * 60 * 1000; // 12 hours

function getSecret(): string {
  const secret = process.env.SESSION_SECRET;
  if (!secret) {
    throw new Error("SESSION_SECRET is not set — required for login to work.");
  }
  return secret;
}

// --- Password hashing (scrypt, built into Node — no extra dependency) ---

export function hashPassword(password: string): string {
  const salt = crypto.randomBytes(16).toString("hex");
  const hash = crypto.scryptSync(password, salt, 64).toString("hex");
  return `${salt}:${hash}`;
}

export function verifyPassword(password: string, stored: string): boolean {
  const [salt, hash] = stored.split(":");
  if (!salt || !hash) return false;
  const candidate = crypto.scryptSync(password, salt, 64).toString("hex");
  const a = Buffer.from(candidate, "hex");
  const b = Buffer.from(hash, "hex");
  return a.length === b.length && crypto.timingSafeEqual(a, b);
}

// --- Session tokens: "<expiry>.<hmac>", signed with SESSION_SECRET ---

export function createSessionToken(): string {
  const expiry = Date.now() + SESSION_TTL_MS;
  const hmac = crypto.createHmac("sha256", getSecret()).update(String(expiry)).digest("hex");
  return `${expiry}.${hmac}`;
}

export function isValidSessionToken(token: string | undefined | null): boolean {
  if (!token) return false;
  const [expiryStr, hmac] = token.split(".");
  if (!expiryStr || !hmac) return false;

  const expiry = Number(expiryStr);
  if (!Number.isFinite(expiry) || expiry < Date.now()) return false;

  const expected = crypto.createHmac("sha256", getSecret()).update(expiryStr).digest("hex");
  const a = Buffer.from(hmac);
  const b = Buffer.from(expected);
  return a.length === b.length && crypto.timingSafeEqual(a, b);
}
