const jwt = require("jsonwebtoken")

function getBearerToken(req) {
  const h = req.headers.authorization
  if (!h) return null
  const [type, token] = h.split(" ")
  if (type !== "Bearer" || !token) return null
  return token
}

module.exports = function requireAuth(req, res, next) {
  const token = getBearerToken(req)
  if (!token) return res.status(401).json({ error: "Token yok" })

  try {
    const decoded = jwt.verify(token, process.env.JWT_ACCESS_SECRET)

    req.auth = {
      userId: typeof decoded.sub === "string" ? Number(decoded.sub) : decoded.sub,
      role: decoded.role,
      jti: decoded.jti,
    }

    if (!req.auth.userId) return res.status(401).json({ error: "Token geçersiz" })
    next()
  } catch (err) {
    return res.status(401).json({ error: "Token geçersiz" })
  }
}
