import type { NextFunction, Request, Response } from "express";
import { verifyAuthToken } from "../lib/jwt";
import { HttpError } from "./errorHandler";

export const AUTH_COOKIE_NAME = "tuesday_token";

declare global {
  namespace Express {
    interface Request {
      userId?: string;
    }
  }
}

export function requireAuth(req: Request, _res: Response, next: NextFunction) {
  const token = req.cookies?.[AUTH_COOKIE_NAME];

  if (!token) {
    next(new HttpError(401, "Not authenticated"));
    return;
  }

  try {
    const payload = verifyAuthToken(token);
    req.userId = payload.userId;
    next();
  } catch {
    next(new HttpError(401, "Invalid or expired session"));
  }
}

/** Sets req.userId when a valid session cookie is present, but never rejects the
 * request — for public routes (like the request portal) that behave differently
 * for logged-in visitors without requiring login. */
export function optionalAuth(req: Request, _res: Response, next: NextFunction) {
  const token = req.cookies?.[AUTH_COOKIE_NAME];
  if (token) {
    try {
      req.userId = verifyAuthToken(token).userId;
    } catch {
      // ignore invalid/expired token — treat as anonymous
    }
  }
  next();
}
