import { getAuth } from 'firebase-admin/auth';
import type { Request } from 'express';
import * as cookie from 'cookie';

export type DecodedAuthInfo = {
  uid: string;
  role: number;
};
/**
 * Verifies the session cookie from the request and returns the decoded auth info.
 * Throws an error if invalid or missing.
 * @param {Request} req - The Express request object containing the session cookie
 * @param {Response} [res] - Optional Express response object for sending error responses
 */
export async function verifySessionFromRequest(
  req: Request,
): Promise<DecodedAuthInfo | null> {
  const cookies = cookie.parse(req.headers.cookie || '');
  const session = cookies.__session;

  if (!session) {
    return null;
  }

  try {
    const decoded = await getAuth().verifySessionCookie(session, true);
    const role = (decoded.role || 0) as number;
    return { uid: decoded.uid, role };
  } catch (err) {
    console.error('[Auth] Session cookie verification failed:', err);
    return null;
  }
}
