import express, { Express } from 'express';
import { Redis } from 'ioredis';
import { applySecurityMiddleware } from '../../interface/middleware/security.middleware';
import { errorHandlerMiddleware } from '../../interface/middleware/error-handler.middleware';
import { ILogger } from '../../application/ports/logger';
import { Middlewares } from './middleware.factory';
import { Routes } from './routes.factory';

export const createApp = (
  logger: ILogger,
  redis: Redis | undefined,
  routes: Routes,
  middlewares: Middlewares,
): Express => {
  const app = express();

  applySecurityMiddleware(app, redis);

  app.use(express.json());
  app.use(express.urlencoded({ extended: true }));

  app.use(middlewares.requestId);
  app.use(middlewares.sanitization);
  app.use(middlewares.auditLogger);

  app.use('/images', routes.imageRouter);
  app.use('/api/v1', routes.apiRouter);

  app.get('/health', (_req, res) => {
    res.status(200).json({ status: 'ok' });
  });

  app.use(errorHandlerMiddleware(logger));

  return app;
};
