import { type Request } from "express";

/**
 * Persist any pending changes to `req.session` to the session store before
 * resolving. Wraps express-session's callback-based `save` in a promise so
 * route handlers can `await` it and guarantee the store write has completed
 * before the HTTP response is flushed.
 *
 * Without this, the default end-hook behavior can race: response headers and
 * body may be sent before the store write finishes, producing intermittent
 * "logged out" / "still logged in" glitches on the very next request.
 */
export function saveSession(req: Request): Promise<void> {
  return new Promise((resolve, reject) => {
    req.session.save((err) => (err ? reject(err) : resolve()));
  });
}

/**
 * Destroy the session and wait for the store deletion to complete before
 * resolving. Mirrors `saveSession` for logout / account-deletion flows so the
 * cookie's backing record is guaranteed to be gone before the response is
 * returned.
 */
export function destroySession(req: Request): Promise<void> {
  return new Promise((resolve, reject) => {
    req.session.destroy((err) => (err ? reject(err) : resolve()));
  });
}
