import { createSession, deleteSession, getUserBySession, getUserByUsername } from './store.js';
import { config } from './config.js';
import { verifyPassword } from './crypto.js';

const cookieName = 'incus_backup_session';

export function requireAuth(req, res, next) {
  const sessionId = readCookie(req, cookieName);
  const user = sessionId ? getUserBySession(sessionId) : null;
  if (!user) {
    res.status(401).json({ error: 'Authentication required.' });
    return;
  }
  req.user = user;
  req.sessionId = sessionId;
  next();
}

export function currentSession(req) {
  const sessionId = readCookie(req, cookieName);
  const user = sessionId ? getUserBySession(sessionId) : null;
  return user ? { sessionId, user } : null;
}

export function login(username, password) {
  const user = getUserByUsername(username);
  if (!user || !verifyPassword(password, user.password_hash)) return null;
  const session = createSession(user.id);
  return { session, user: { id: user.id, username: user.username } };
}

export function logout(sessionId) {
  if (sessionId) deleteSession(sessionId);
}

export function setSessionCookie(res, session) {
  res.setHeader('Set-Cookie', [
    cookieHeader(cookieName, session.id, `Expires=${session.expiresAt.toUTCString()}`),
  ]);
}

export function clearSessionCookie(res) {
  res.setHeader('Set-Cookie', [cookieHeader(cookieName, '', 'Max-Age=0')]);
}

function readCookie(req, name) {
  const header = req.headers.cookie || '';
  for (const part of header.split(';')) {
    const [key, ...value] = part.trim().split('=');
    if (key === name) return decodeURIComponent(value.join('='));
  }
  return '';
}

function cookieHeader(name, value, lifetime) {
  const secure = config.sessionCookieSecure ? '; Secure' : '';
  return `${name}=${encodeURIComponent(value)}; Path=/; HttpOnly; SameSite=Strict${secure}; ${lifetime}`;
}
