import { IncomingMessage } from "node:http";
import { Session, SessionId } from "../types/user.js";
import getSession from "./getSession.js";

/**
 * Get the session object from a request object
 * @param req The request object to get the session from. Accepts anything that extends IncomingMessage.
 * @returns The session object.
 */
export default async function getSessionFromReq<T extends IncomingMessage>(req: T): Promise<Session> {
    const sessionId = req.headers["x-session-id"];
    if (!sessionId || typeof sessionId !== "string") {
        throw new Error("No session ID provided in request.");
    }

    return getSession(parseInt(sessionId) as SessionId);
}