import { NextFunction, Request, Response } from "express";
import jwt from "jsonwebtoken";
import dotenv from "dotenv";
import { authBasicRoute } from "../endpoints/AuthPoint.js";
import { AuthPayload } from "../dtos/AuthPayload.js";

dotenv.config();

declare global {
  namespace Express {
    interface Request {
      currentUser?: AuthPayload;
    }
  }
}

const JWT_SECRET = process.env.JWT_SECRET;

if (!JWT_SECRET) {
  throw new Error("JWT_SECRET not defined");
}

export const authentication = (
  req: Request,
  res: Response,
  next: NextFunction
) => {
   // allow unauthenticated access to auth routes
  if (req.path.startsWith(authBasicRoute)) {
    return next();
  }

  const header = req.headers.authorization;
  if (!header) {
    return res.status(401).json({ message: "Unauthorized" });
  }

  const token = header.split(" ")[1];
  if (!token) {
    return res.status(401).json({ message: "Unauthorized" });
  }

  const JWT_SECRET = process.env.JWT_SECRET;
  if (!JWT_SECRET) {
    throw new Error("JWT_SECRET not defined");
  }

  try {
    const decoded = jwt.verify(token, JWT_SECRET) as AuthPayload;
    req.currentUser = decoded;
    next();
  } catch {
    return res.status(401).json({ message: "Unauthorized" });
  }
};
