import { Router } from 'express';

import { sequelize } from '../config/database';
import { authenticateToken } from '../middlewares/auth.middleware';
import { requireAdmin } from '../middlewares/authorization.middleware';
import {
  authLimiter,
  uploadLimiter,
  adminLimiter,
  aiLimiter,
  webhookLimiter,
  generalApiLimiter,
} from '../middlewares/rateLimiter.middleware';

import authRoutes from './auth.routes';
import workflowRoutes from './workflow.routes';
import summaryRoutes from './summary.routes';
import userRoutes from './user.routes';
import userPreferenceRoutes from './userPreference.routes';
import documentRoutes from './document.routes';
import tatRoutes from './tat.routes';
import adminRoutes from './admin.routes';
import debugRoutes from './debug.routes';
import configRoutes from './config.routes';
import dashboardRoutes from './dashboard.routes';
import notificationRoutes from './notification.routes';
import conclusionRoutes from './conclusion.routes';
import aiRoutes from './ai.routes';
import dealerClaimRoutes from './dealerClaim.routes';
import templateRoutes from './template.routes';
import dealerRoutes from './dealer.routes';
import dmsWebhookRoutes from './dmsWebhook.routes';
import apiTokenRoutes from './apiToken.routes';
import antivirusRoutes from './antivirus.routes';
import dealerExternalRoutes from './dealerExternal.routes';
import form16Routes from './form16.routes';
import hsnSacCodeRoutes from './hsnSacCode.routes';
import cpcCdcRoutes from './cpc-cdc.routes';
import cpcPermissionRoutes from './cpc-permission.routes';


const router = Router();

// Health check route
router.get('/health', (_req, res) => {
  res.status(200).json({
    status: 'OK',
    timestamp: new Date(),
    service: 're-workflow-backend'
  });
});

// Database connectivity check (for ops/testing)
router.get('/health/db', async (_req, res) => {
  try {
    await sequelize.authenticate();
    res.status(200).json({
      status: 'OK',
      database: 'connected',
      timestamp: new Date()
    });
  } catch (err: any) {
    res.status(503).json({
      status: 'ERROR',
      database: 'disconnected',
      error: err?.message || 'Unknown error',
      timestamp: new Date()
    });
  }
});

// API routes (with rate limiters)
// ── Auth & Admin (strict limits) ──
router.use('/auth', authLimiter, authRoutes);                           // 20 req/15min
router.use('/admin', adminLimiter, adminRoutes);                        // 30 req/15min
router.use('/debug', authenticateToken, requireAdmin, adminLimiter, debugRoutes); // 30 req/15min

// ── File uploads (moderate limits) ──
router.use('/documents', uploadLimiter, documentRoutes);                // 50 req/15min
router.use('/antivirus', uploadLimiter, antivirusRoutes);               // 50 req/15min

// ── AI (resource-intensive) ──
router.use('/ai', aiLimiter, aiRoutes);                                 // 20 req/15min

// ── External webhooks (burst-friendly) ──
router.use('/webhooks/dms', webhookLimiter, dmsWebhookRoutes);          // 100 req/15min

// ── Dealer claims (SAP/PWC rate limiting at individual route level in dealerClaim.routes.ts) ──
router.use('/dealer-claims', generalApiLimiter, dealerClaimRoutes);     // 200 req/15min (SAP routes have additional stricter limits)

// ── Standard API routes (general limits) ──
router.use('/config', configRoutes);                                    // Public config — no limiter
router.use('/workflows', generalApiLimiter, workflowRoutes);            // 200 req/15min
router.use('/users', generalApiLimiter, userRoutes);                    // 200 req/15min
router.use('/user/preferences', generalApiLimiter, userPreferenceRoutes); // 200 req/15min
router.use('/tat', generalApiLimiter, tatRoutes);                       // 200 req/15min
router.use('/dashboard', generalApiLimiter, dashboardRoutes);           // 200 req/15min
router.use('/notifications', generalApiLimiter, notificationRoutes);    // 200 req/15min
router.use('/conclusions', generalApiLimiter, conclusionRoutes);        // 200 req/15min
router.use('/summaries', generalApiLimiter, summaryRoutes);             // 200 req/15min
router.use('/templates', generalApiLimiter, templateRoutes);            // 200 req/15min
router.use('/dealers', generalApiLimiter, dealerRoutes);                // 200 req/15min
router.use('/dealers-external', generalApiLimiter, dealerExternalRoutes); // 200 req/15min
router.use('/form16', uploadLimiter, form16Routes);                     // 50 req/15min (file uploads: extract, submissions, 26as)
router.use('/api-tokens', authLimiter, apiTokenRoutes);                 // 20 req/15min (sensitive — same as auth)
router.use('/hsn-sac', generalApiLimiter, hsnSacCodeRoutes);            // 200 req/15min
router.use('/cpc-csd', generalApiLimiter, cpcPermissionRoutes);         // 200 req/15min (canonical)
router.use('/cpc-csd', generalApiLimiter, cpcCdcRoutes);



export default router;

