const jwt = require("jsonwebtoken")
const { getOrCacheUserModeration } = require("../services/redis/userModerationCache.service")

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 = async 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" })

    const moderation = await getOrCacheUserModeration(req.auth.userId)
    if (moderation?.disabledAt) {
      return res.status(403).json({ error: "Hesap devre disi" })
    }

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