'use strict';

const crypto = require('crypto');

function createToken(secret, sessionHours) {
  const expires = Date.now() + sessionHours * 3600 * 1000;
  const payload = JSON.stringify({ auth: true, exp: expires });
  const b64 = Buffer.from(payload).toString('base64url');
  const sig = crypto.createHmac('sha256', secret).update(b64).digest('base64url');
  return `${b64}.${sig}`;
}

function verifyToken(token, secret) {
  if (!token || typeof token !== 'string') return false;
  const parts = token.split('.');
  if (parts.length !== 2) return false;
  const [b64, sig] = parts;
  const expectedSig = crypto.createHmac('sha256', secret).update(b64).digest('base64url');
  try {
    const a = Buffer.from(sig);
    const b = Buffer.from(expectedSig);
    if (a.length !== b.length) return false;
    if (!crypto.timingSafeEqual(a, b)) return false;
    const payload = JSON.parse(Buffer.from(b64, 'base64url').toString());
    return payload.auth === true && payload.exp > Date.now();
  } catch (_) {
    return false;
  }
}

function parseCookies(header) {
  const cookies = {};
  if (!header) return cookies;
  for (const c of header.split(';')) {
    const idx = c.indexOf('=');
    if (idx < 0) continue;
    const n = c.slice(0, idx).trim();
    const v = c.slice(idx + 1).trim();
    if (n) cookies[n] = decodeURIComponent(v);
  }
  return cookies;
}

function checkPassword(submitted, expected) {
  if (typeof submitted !== 'string' || typeof expected !== 'string') return false;
  const a = Buffer.from(submitted);
  const b = Buffer.from(expected);
  if (a.length !== b.length) return false;
  return crypto.timingSafeEqual(a, b);
}

module.exports = { createToken, verifyToken, parseCookies, checkPassword };
