const jwt = require('jsonwebtoken');
const { getPool } = require('../shared/config/database');

const JWT_SECRET = process.env.SSO_JWT_SECRET;

function extractToken(req) {
  const authHeader = req.headers['authorization'];
  if (authHeader && authHeader.startsWith('Bearer ')) {
    return authHeader.split(' ')[1];
  }
  return null;
}

function requireAuth(req, res, next) {
  const token = extractToken(req);
  if (!token) {
    return res.status(401).json({ success: false, error: '인증이 필요합니다' });
  }
  try {
    const decoded = jwt.verify(token, JWT_SECRET);
    req.user = decoded;
    next();
  } catch {
    return res.status(401).json({ success: false, error: '유효하지 않은 토큰입니다' });
  }
}

function requireAdmin(req, res, next) {
  const token = extractToken(req);
  if (!token) {
    return res.status(401).json({ success: false, error: '인증이 필요합니다' });
  }
  try {
    const decoded = jwt.verify(token, JWT_SECRET);
    if (!['admin', 'system'].includes((decoded.role || '').toLowerCase())) {
      return res.status(403).json({ success: false, error: '관리자 권한이 필요합니다' });
    }
    req.user = decoded;
    next();
  } catch {
    return res.status(401).json({ success: false, error: '유효하지 않은 토큰입니다' });
  }
}

// requirePage: shared 미들웨어 사용
const { createRequirePage } = require('../../../shared/middleware/pagePermission');
const requirePage = createRequirePage(() => getPool());

function requireSupportTeam(req, res, next) {
  const token = extractToken(req);
  if (!token) {
    return res.status(401).json({ success: false, error: '인증이 필요합니다' });
  }
  try {
    const decoded = jwt.verify(token, JWT_SECRET);
    if (!['support_team', 'admin', 'system'].includes((decoded.role || '').toLowerCase())) {
      return res.status(403).json({ success: false, error: '지원팀 이상 권한이 필요합니다' });
    }
    req.user = decoded;
    next();
  } catch {
    return res.status(401).json({ success: false, error: '유효하지 않은 토큰입니다' });
  }
}

module.exports = { getPool, extractToken, requireAuth, requireAdmin, requireSupportTeam, requirePage };
