import express, { type Request, type Response, type NextFunction } from 'express';
import 'dotenv/config';
import { userRouter } from './routes/userRoutes';
import { errorHandler } from './middleware/errorHandler';
import cors from 'cors';
import logger from './logger';

export function createApp() {
  const app = express();

  app.use(cors());
  app.use(express.json());
  app.use(express.urlencoded({ extended: true }));
  app.use('/users', userRouter);
  app.use(errorHandler);

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

  app.use((req: Request, res: Response, next: NextFunction) => {
    const start = Date.now();
    res.on('finish', () => {
      logger.info({
        method: req.method,
        url: req.originalUrl,
        status: res.statusCode,
        ms: Date.now() - start,
      });
    });
    next();
  });

  return app;
}