// src/tests/utils/createTestApp.ts
import express, { type Router } from 'express';
import type { Logger } from 'pino';
import { errorHandler } from '../../middleware/errorHandler';
import { mockLogger } from './mockLogger';
import type { UserProfile } from '../../types';

// Augment the Express Request type to include our custom `log` and `user` properties.
// This uses the modern module augmentation syntax instead of `namespace`.
declare module 'express-serve-static-core' {
  interface Request {
    log: Logger;
    user?: UserProfile;
  }
}
interface CreateAppOptions {
  router: Router;
  basePath: string;
  authenticatedUser?: UserProfile;
}

/**
 * Creates a standardized Express application instance for integration tests.
 * It includes JSON parsing, a mock logger, an optional authenticated user,
 * the specified router, and the global error handler.
 */
export const createTestApp = ({ router, basePath, authenticatedUser }: CreateAppOptions) => {
  const app = express();
  app.use(express.json({ strict: false }));

  // Inject the mock logger and authenticated user into every request.
  app.use((req, res, next) => {
    req.log = mockLogger;
    if (authenticatedUser) req.user = authenticatedUser;
    next();
  });

  app.use(basePath, router);
  app.use(errorHandler);
  return app;
};