import express from 'express';
import cors from 'cors';
import { loadCustomerSecurityPolicy } from '@dbis/integration-foundation';
import { createExchangeRouter, exchangePort } from './api/routes/exchange';
import { exchangeRateLimiter } from './middleware/rate-limit';

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 startServer(): void {
  const app = express();
  app.use(cors(corsOptions()));
  app.use(express.json());
  app.use('/api/v1/exchange', exchangeRateLimiter, createExchangeRouter());
  const p = exchangePort();
  app.listen(p, () => {
    console.log(`DBIS Exchange (Pancake-style) on http://localhost:${p}/api/v1/exchange`);
  });
}
