import jwt from "jsonwebtoken";
import yenv from "yenv";
import { TokenBlacklist } from "../database/auth/tokenBlacklist";
import { User } from "../database/user/user";
const env = yenv("env.yaml", { env: "development" });

 export const isAuthenticated = async (req: any, res: any, next: any): Promise<void> => {
 try {
  const token = getToken(req.headers.authorization);
   if (!token) {
     return res.status(401).send("Authorization token is missing");
   }

   const decode: { [key: string]: any } = jwt.verify(token, env.JWT_SECRET as string) as { [key: string]: any };

   const isBlacklisted = await TokenBlacklist.findOne({
     where: { token }
   });

   if (isBlacklisted) {
     return res.status(401).send("Token has been revoked");
   }

   const user = await User.findOne({ where: { id: decode.userId } });
   if (!user) {
     return res.status(401).send("User not found");
   }

   req.user = user;
   req.tokenPayload = decode;

   next();
 } catch (error) {
   res.status(401).send("Invalid token");
 }
};

const getToken = (authHeader: string | undefined) => {
  if (authHeader?.startsWith("Bearer ")) {
    return authHeader.slice(7);
  }

  return null;
};
