const jwt = require('jsonwebtoken');
const redis = require('../config/redis');

async function requireAuth(req, res, next) {
  const header = req.headers.authorization;
  if (!header?.startsWith('Bearer ')) {
    return res.status(401).json({ error: '인증이 필요합니다' });
  }
  const token = header.slice(7);
  try {
    // 블랙리스트 확인 (로그아웃된 토큰)
    const blocked = await redis.get(`bl:${token}`);
    if (blocked) return res.status(401).json({ error: '만료된 토큰입니다' });

    const payload = jwt.verify(token, process.env.JWT_SECRET);
    req.user = payload;
    req.token = token;
    next();
  } catch {
    return res.status(401).json({ error: '유효하지 않은 토큰입니다' });
  }
}

function requireRole(...roles) {
  return (req, res, next) => {
    if (!roles.includes(req.user?.role)) {
      return res.status(403).json({ error: '권한이 없습니다' });
    }
    next();
  };
}

module.exports = { requireAuth, requireRole };
