const cors = require('cors');
const express = require('express');
const env = require('./config/env');
const routes = require('./routes');
const { errorMiddleware } = require('./middlewares/error.middleware');

const app = express();

app.disable('x-powered-by');

app.use(
  cors({
    origin: (origin, callback) => {
      if (!origin) {
        callback(null, true);
        return;
      }
      if (env.CORS_ORIGINS.includes('*') || env.CORS_ORIGINS.includes(origin)) {
        callback(null, true);
        return;
      }
      callback(new Error(`Origen no permitido: ${origin}`));
    }
  })
);

app.use(express.json({ limit: '1mb' }));
app.use('/api', routes);

app.use(errorMiddleware);

module.exports = { app };
