import { Response, NextFunction } from "express";
import jwt from "jsonwebtoken";
import AuthConfig from "../config/authConfig";
import { CustomRequest, jwtPayload } from "../interfaces/auth";

export const optionalAuth = (
  req: CustomRequest,
  res: Response,
  next: NextFunction
) => {
  const tokenHeader = req.headers["authorization"];
  if (!tokenHeader) {
    return next();
  }
  const token = tokenHeader.split(" ")[1];
  if (!token) {
    return next();
  }
  try {
    const decoded = jwt.verify(
      token,
      String(AuthConfig.JWT_SECRET)
    ) as jwtPayload;
    req.userId = decoded.id;
    req.email = decoded.email;
    req.role = decoded.role;
  } catch {
    /* public request without user context */
  }
  next();
};
