import express from 'express';
import cors from 'cors';
import { loadCustomerSecurityPolicy } from '@dbis/integration-foundation';
import { createSettlementRouter } from './api/routes/settlement';
import { settlementRateLimiter } from './middleware/rate-limit';
import { port } from './config';

function corsOptions(): cors.CorsOptions {
  const policy = loadCustomerSecurityPolicy();
  const origins = policy.corsOrigins.filter(Boolean);
  if (!origins.length) return {};
  return {
    origin(origin, cb) {
      if (!origin || origins.includes(origin)) cb(null, true);
      else cb(new Error('CORS not allowed'));
    },
  };
}

export function createApp() {
  const app = express();
  app.use(cors(corsOptions()));
  app.use(express.json({ limit: '2mb' }));
  app.use(express.text({ type: 'text/plain', limit: '2mb' }));
  app.use('/api/v1/settlement', settlementRateLimiter, createSettlementRouter());
  return app;
}

export function startServer(): void {
  const app = createApp();
  const p = port();
  app.listen(p, () => {
    console.log(`OMNL settlement middleware listening on http://localhost:${p}/api/v1/settlement`);
  });
}
