import express from 'express';
import multer from 'multer';
import { authenticateToken } from '../middlewares/auth.middleware';
import { asyncHandler } from '../middlewares/errorHandler.middleware';
import { generalApiLimiter } from '../middlewares/rateLimiter.middleware';
import { requireCpcCdcAccess } from '../middlewares/cpcPermission.middleware';
import { cpcCdcController } from '../controllers/CpcCdcController';
import { CpcReportController } from '../controllers/CpcReportController';

const memoryUpload = multer({
  storage: multer.memoryStorage(),
  limits: { fileSize: 15 * 1024 * 1024 },
  fileFilter: (_req, file, cb) => {
    const lowerName = String(file.originalname || '').toLowerCase();
    const lowerMime = String(file.mimetype || '').toLowerCase();
    const isZip = lowerName.endsWith('.zip') || lowerMime.includes('zip');
    if (isZip) {
      cb(new Error('ZIP files are not allowed for CPC-CSD validation'));
      return;
    }
    cb(null, true);
  }
});

const cpcReportController = new CpcReportController();

const authLim = [authenticateToken, requireCpcCdcAccess, generalApiLimiter];

/**
 * CPC-CSD (`CPC-CSD/server`) style URLs on re-workflow:
 * - `POST /api/upload`
 * - `GET /api/documents/...` (same order as legacy router)
 * - `POST /api/v1/ocr/validate` | `validate-upload` | `upload`
 * - `GET /api/v1/ocr/report/...`
 *
 * Disable with `CPC_LEGACY_COMPAT_ROUTES=false`.
 */
export function registerCpcCsdCompatRoutes(app: express.Application): void {
  if (String(process.env.CPC_LEGACY_COMPAT_ROUTES || '').toLowerCase() === 'false') {
    return;
  }

  app.post(
    '/api/upload',
    ...authLim,
    memoryUpload.single('file'),
    asyncHandler(cpcCdcController.uploadBareFile.bind(cpcCdcController))
  );

  const documentsRouter = express.Router();
  documentsRouter.use(...authLim);
  documentsRouter.get('/analytics', asyncHandler(cpcCdcController.getAnalytics.bind(cpcCdcController)));
  documentsRouter.get('/history', asyncHandler(cpcCdcController.getClaimHistory.bind(cpcCdcController)));
  documentsRouter.get('/recent', asyncHandler(cpcCdcController.getRecentDocuments.bind(cpcCdcController)));
  documentsRouter.get('/:id/file', asyncHandler(cpcCdcController.getDocumentFile.bind(cpcCdcController)));
  documentsRouter.get('/:id', asyncHandler(cpcCdcController.getDocumentById.bind(cpcCdcController)));
  documentsRouter.put('/:id/status', asyncHandler(cpcCdcController.updateDocumentStatus.bind(cpcCdcController)));
  documentsRouter.delete('/:id', asyncHandler(cpcCdcController.deleteDocument.bind(cpcCdcController)));
  app.use('/api/documents', documentsRouter);

  app.post(
    '/api/v1/ocr/validate',
    ...authLim,
    asyncHandler(cpcCdcController.validateDocumentByUrlStub.bind(cpcCdcController))
  );
  app.post(
    '/api/v1/ocr/validate-upload',
    ...authLim,
    memoryUpload.single('file'),
    asyncHandler(cpcCdcController.validateDocumentUpload.bind(cpcCdcController))
  );
  app.post(
    '/api/v1/ocr/upload',
    ...authLim,
    memoryUpload.array('files', 20),
    asyncHandler(cpcCdcController.validateDocumentUpload.bind(cpcCdcController))
  );

  app.get(
    '/api/v1/ocr/report/all/download',
    ...authLim,
    asyncHandler(cpcReportController.downloadAllReport.bind(cpcReportController))
  );
  app.get(
    '/api/v1/ocr/report/:claimId/download',
    ...authLim,
    asyncHandler(cpcReportController.downloadReport.bind(cpcReportController))
  );
}
