/**
 * SSO Auth Routes
 */

const express = require('express');
const router = express.Router();
const authController = require('../controllers/authController');
const jwt = require('jsonwebtoken');

// Middleware: admin 체크
function requireAdmin(req, res, next) {
  const token = req.headers['authorization']?.split(' ')[1];
  if (!token) {
    return res.status(401).json({ success: false, error: '인증이 필요합니다' });
  }
  try {
    const decoded = jwt.verify(token, process.env.SSO_JWT_SECRET);
    if (!['admin', 'system'].includes(decoded.role)) {
      return res.status(403).json({ success: false, error: '관리자 권한이 필요합니다' });
    }
    req.user = decoded;
    next();
  } catch {
    return res.status(401).json({ success: false, error: '유효하지 않은 토큰입니다' });
  }
}

// 공개 엔드포인트
router.post('/login', authController.login);
router.post('/login/form', express.urlencoded({ extended: true }), authController.loginForm);
router.get('/validate', authController.validate);
router.get('/me', authController.me);
router.post('/refresh', authController.refresh);
router.post('/logout', authController.logout);

// 관리자 엔드포인트
router.get('/users', requireAdmin, authController.getUsers);
router.post('/users', requireAdmin, authController.createUser);
router.put('/users/:id', requireAdmin, authController.updateUser);
router.delete('/users/:id', requireAdmin, authController.deleteUser);

module.exports = router;
