/**
 * 라우트 설정
 *
 * 애플리케이션의 모든 라우트를 등록하는 중앙화된 설정 파일
 *
 * @author TK-FB-Project
 * @since 2025-12-11
 */

const swaggerUi = require('swagger-ui-express');
const swaggerSpec = require('./swagger');
const { verifyToken } = require('../middlewares/auth');
const { activityLogger } = require('../middlewares/activityLogger');
const logger = require('../utils/logger');

/**
 * 모든 라우트를 Express 앱에 등록
 * @param {Express.Application} app - Express 애플리케이션 인스턴스
 */
function setupRoutes(app) {
  // 라우터 가져오기
  const authRoutes = require('../routes/authRoutes');
  const projectRoutes = require('../routes/projectRoutes');
  const workerRoutes = require('../routes/workerRoutes');
  const workReportRoutes = require('../routes/workReportRoutes');
  const toolsRoute = require('../routes/toolsRoute');
  const uploadRoutes = require('../routes/uploadRoutes');
  const uploadBgRoutes = require('../routes/uploadBgRoutes');
  const dailyIssueReportRoutes = require('../routes/dailyIssueReportRoutes');
  const issueTypeRoutes = require('../routes/issueTypeRoutes');
  const healthRoutes = require('../routes/healthRoutes');
  const dailyWorkReportRoutes = require('../routes/dailyWorkReportRoutes');
  const workAnalysisRoutes = require('../routes/workAnalysisRoutes');
  const analysisRoutes = require('../routes/analysisRoutes');
  const systemRoutes = require('../routes/systemRoutes');
  const performanceRoutes = require('../routes/performanceRoutes');
  const userRoutes = require('../routes/userRoutes');
  const setupRoutes = require('../routes/setupRoutes');
  const workReportAnalysisRoutes = require('../routes/workReportAnalysisRoutes');
  const attendanceRoutes = require('../routes/attendanceRoutes');
  const monthlyStatusRoutes = require('../routes/monthlyStatusRoutes');
  const pageAccessRoutes = require('../routes/pageAccessRoutes');
  const workplaceRoutes = require('../routes/workplaceRoutes');
  const equipmentRoutes = require('../routes/equipmentRoutes');
  const taskRoutes = require('../routes/taskRoutes');
  const tbmRoutes = require('../routes/tbmRoutes');
  const vacationRequestRoutes = require('../routes/vacationRequestRoutes');
  const vacationTypeRoutes = require('../routes/vacationTypeRoutes');
  const vacationBalanceRoutes = require('../routes/vacationBalanceRoutes');
  const workIssueRoutes = require('../routes/workIssueRoutes');
  const departmentRoutes = require('../routes/departmentRoutes');
  const patrolRoutes = require('../routes/patrolRoutes');
  const purchaseRequestRoutes = require('../routes/purchaseRequestRoutes');
  const purchaseRoutes = require('../routes/purchaseRoutes');
  const settlementRoutes = require('../routes/settlementRoutes');
  const scheduleRoutes = require('../routes/scheduleRoutes');
  const meetingRoutes = require('../routes/meetingRoutes');
  const proxyInputRoutes = require('../routes/proxyInputRoutes');
  const monthlyComparisonRoutes = require('../routes/monthlyComparisonRoutes');
  const dashboardRoutes = require('../routes/dashboardRoutes');

  // Rate Limiters 설정
  const rateLimit = require('express-rate-limit');

  const loginLimiter = rateLimit({
    windowMs: 15 * 60 * 1000, // 15분
    max: 5, // 최대 5회
    message: '너무 많은 로그인 시도가 있었습니다. 잠시 후 다시 시도해주세요.',
    standardHeaders: true,
    legacyHeaders: false
  });

  const apiLimiter = rateLimit({
    windowMs: 1 * 60 * 1000, // 1분
    max: 1000, // 최대 1000회 (기존 100회에서 대폭 증가)
    message: 'API 요청 한도를 초과했습니다. 잠시 후 다시 시도해주세요.',
    standardHeaders: true,
    legacyHeaders: false,
    // 관리자 및 시스템 계정은 rate limit 제외
    skip: (req) => {
      // 인증된 사용자 정보 확인
      if (req.user && (req.user.access_level === 'system' || req.user.access_level === 'admin')) {
        return true; // rate limit 건너뛰기
      }
      return false;
    }
  });

  // 모든 API 요청에 활동 로거 적용
  app.use('/api/*', activityLogger);

  // 인증 불필요 경로 - 로그인
  app.use('/api/auth', loginLimiter, authRoutes);

  // DB 설정 라우트 (개발용)
  app.use('/api/setup', setupRoutes);

  // Health check
  app.use('/api/health', healthRoutes);

  // 인증이 필요 없는 공개 경로 목록
  const publicPaths = [
    '/api/auth/login',
    '/api/auth/refresh-token',
    '/api/auth/check-password-strength',
    '/api/health',
    '/api/ping',
    '/api/status',
    '/api/setup/setup-attendance-db',
    '/api/setup/setup-monthly-status',
    '/api/setup/add-overtime-warning',
    '/api/setup/migrate-existing-data',
    '/api/setup/check-data-status',
    '/api/monthly-status/calendar',
    '/api/monthly-status/daily-details',
  ];

  // 인증 미들웨어 - 공개 경로를 제외한 모든 API (rate limiter보다 먼저 실행)
  app.use('/api/*', (req, res, next) => {
    const isPublicPath = publicPaths.some(path => {
      return req.originalUrl === path ||
             req.originalUrl.startsWith(path + '?') ||
             req.originalUrl.startsWith(path + '/');
    });

    if (isPublicPath) {
      logger.debug('공개 경로 허용', { url: req.originalUrl });
      return next();
    }

    logger.debug('인증 필요 경로', { url: req.originalUrl });
    verifyToken(req, res, next);
  });

  // 인증 후 일반 API에 속도 제한 적용 (인증된 사용자 정보로 skip 판단)
  app.use('/api/', apiLimiter);

  // 인증된 사용자만 접근 가능한 라우트들
  app.use('/api/issue-reports', dailyIssueReportRoutes);
  app.use('/api/issue-types', issueTypeRoutes);
  app.use('/api/workers', workerRoutes);
  app.use('/api/daily-work-reports', dailyWorkReportRoutes);
  app.use('/api/work-analysis', workAnalysisRoutes);
  app.use('/api/analysis', analysisRoutes);
  app.use('/api/daily-work-reports-analysis', workReportAnalysisRoutes);
  app.use('/api/attendance', attendanceRoutes);
  app.use('/api/monthly-status', monthlyStatusRoutes);
  app.use('/api/workreports', workReportRoutes);
  app.use('/api/system', systemRoutes);
  app.use('/api/uploads', uploadRoutes);
  app.use('/api/performance', performanceRoutes);
  app.use('/api/projects', projectRoutes);
  app.use('/api/tools', toolsRoute);
  app.use('/api', pageAccessRoutes); // 페이지 접근 권한 관리 (userRoutes보다 먼저 등록 - /users/:id/page-access 매칭 우선)
  app.use('/api/users', userRoutes);
  app.use('/api/workplaces', workplaceRoutes);
  app.use('/api/equipments', equipmentRoutes);
  app.use('/api/tasks', taskRoutes);
  app.use('/api/vacation-requests', vacationRequestRoutes); // 휴가 신청 관리
  app.use('/api/vacation-types', vacationTypeRoutes); // 휴가 유형 관리
  app.use('/api/vacation-balances', vacationBalanceRoutes); // 휴가 잔액 관리
  app.use('/api/tbm', tbmRoutes); // TBM 시스템
  app.use('/api/work-issues', workIssueRoutes); // 카테고리/아이템 + 신고 조회 (같은 MariaDB 공유)
  app.use('/api/departments', departmentRoutes); // 부서 관리
  app.use('/api/patrol', patrolRoutes); // 일일순회점검 시스템
  app.use('/api/purchase-requests', purchaseRequestRoutes); // 구매신청
  app.use('/api/purchases', purchaseRoutes); // 구매 내역
  app.use('/api/settlements', settlementRoutes); // 월간 정산
  app.use('/api/schedule', scheduleRoutes); // 공정표
  app.use('/api/meetings', meetingRoutes); // 생산회의록
  app.use('/api/proxy-input', proxyInputRoutes); // 대리입력 + 일별현황
  app.use('/api/monthly-comparison', monthlyComparisonRoutes); // 월간 비교·확인·정산
  app.use('/api/dashboard', dashboardRoutes); // 대시보드 개인 요약
  app.use('/api', uploadBgRoutes);

  // Swagger API 문서
  app.use('/api-docs', swaggerUi.serve, swaggerUi.setup(swaggerSpec, {
    explorer: true,
    customCss: '.swagger-ui .topbar { display: none }',
    customSiteTitle: 'TK Work Management API',
    swaggerOptions: {
      persistAuthorization: true,
      displayRequestDuration: true,
      docExpansion: 'none',
      filter: true,
      showExtensions: true,
      showCommonExtensions: true
    }
  }));

  app.get('/api-docs.json', (req, res) => {
    res.setHeader('Content-Type', 'application/json');
    res.send(swaggerSpec);
  });

  logger.info('라우트 설정 완료');
}

module.exports = setupRoutes;
