import jwt from "jsonwebtoken";
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]; // Extract the token from 'Bearer <token>'
    const isCustomAuth = token.length < 500; // Check if it's a custom JWT or a third-party auth

    let decodedData;

    if (token && isCustomAuth) {
      decodedData = jwt.verify(token, secret); // Verify the custom JWT
      req.userId = decodedData?.id; // Set the user ID to request object
    } else {
      decodedData = jwt.decode(token); // Decode third-party tokens (e.g., Google OAuth)
      req.userId = decodedData?.sub; // Usually for third-party tokens, user ID is in `sub`
    }

    next(); // Continue to the next middleware or route handler
  } catch (error) {
    console.log(error);
    res.status(403).json({ message: "Authentication failed" });
  }
};

export default auth;
