const jwt = require("jsonwebtoken")

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

module.exports = function optionalAuth(req, res, next) {
  const token = getBearerToken(req)
  if (!token) return next()

  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,
    }
    return next()
  } catch (err) {
    return res.status(401).json({ error: "Token geçersiz" })
  }
}
