import jwt from "jsonwebtoken";
import type { Request, Response } from "express";
import { env } from "../env";
import type { SessionUser } from "../types";

export const SESSION_COOKIE = "eatme_session";
const SESSION_TTL_SECONDS = 60 * 60 * 12; // 12h

export function issueSession(res: Response, user: SessionUser): void {
  const token = jwt.sign(user, env.jwtSecret, { expiresIn: SESSION_TTL_SECONDS });
  res.cookie(SESSION_COOKIE, token, {
    httpOnly: true,
    secure: env.cookieSecure,
    sameSite: "lax",
    maxAge: SESSION_TTL_SECONDS * 1000,
    path: "/",
  });
}

export function clearSession(res: Response): void {
  res.clearCookie(SESSION_COOKIE, { path: "/" });
}

export function readSession(req: Request): SessionUser | null {
  const token = req.cookies?.[SESSION_COOKIE];
  if (!token) return null;
  try {
    return jwt.verify(token, env.jwtSecret) as SessionUser;
  } catch {
    return null;
  }
}
