import jwt from "jsonwebtoken";
import {User} from "../models/user.js";

export const authenticate = async (req, res, next) => {
  try {
    const authHeader = req.headers.authorization;

    if (!authHeader || !authHeader.startsWith("Bearer ")) {
      return res.status(401).json({ message: "Unauthorized: No token provided" });
    }

    const token = authHeader.split(" ")[1];
    const decoded = jwt.verify(token, process.env.JWT_SECRET);

    // Attach user info to request
    const user = await User.findById(decoded.userId).select("_id userName email");
    if (!user) return res.status(401).json({ message: "Unauthorized: User not found" });

    req.user = { id: user._id, userName: user.userName, email: user.email };
    next();
  } catch (err) {
    console.error("Auth middleware error:", err);
    if (err.name === 'TokenExpiredError') {
      return res.status(401).json({ message: "Unauthorized: Token expired" });
    }
    return res.status(401).json({ message: "Unauthorized: Invalid token" });
  }
};
