import jwt from "jsonwebtoken";

import { env } from "../config/env.js";

const getRequestToken = (req) => {
  const cookieToken = req.cookies?.[env.jwtCookieName];

  if (cookieToken) {
    return cookieToken;
  }

  const authHeader = req.headers.authorization;

  if (authHeader?.startsWith("Bearer ")) {
    return authHeader.split(" ")[1];
  }

  return null;
};

export const authenticateToken = (req, res, next) => {
  const token = getRequestToken(req);

  if (!token) {
    return res.status(401).json({
      message: "Authentication required.",
    });
  }

  try {
    req.user = jwt.verify(token, env.jwtSecret);
    return next();
  } catch (error) {
    return res.status(401).json({
      message: "Invalid or expired token.",
    });
  }
};
