import jwt from "jsonwebtoken";
import UserModel from "../models/user.js"
import dotenv from "dotenv";

dotenv.config();

const secret = process.env.SECRET_KEY

const auth = async (req, res, next) => {
  try {

     // Check if the authorization header exists
     if (!req.headers.authorization) {
      return res.status(401).json({ message: "Authorization header missing" });
    }
    
    const token = req.headers.authorization.split(" ")[1];
    const isCustomAuth = token.length < 500;
    let decodedData;
    if (token && isCustomAuth) {
      decodedData = jwt.verify(token, secret);
      req.userId = decodedData?.id;
    } else {
      decodedData = jwt.decode(token);
      // const googleId = decodedData?.sub.toString();
      // const user = await UserModel.findOne({ googleId });
      // req.userId = user?._id;
      req.userId = decodedData?.id;
    }
    next();
  } catch (error) {
    console.log(error);
  }
};

export default auth;
