import { Request, Response, NextFunction } from 'express';
import { ZodError } from 'zod';
import { DomainError } from '../../domain/errors/domain-error';
import { ValidationError } from '../../domain/errors/validation-error';
import { ILogger } from '../../application/ports/logger';

export const errorHandlerMiddleware = (logger: ILogger) => {
  // eslint-disable-next-line @typescript-eslint/no-unused-vars
  return (error: Error, _req: Request, res: Response, _next: NextFunction): void => {
    if (error instanceof DomainError) {
      const response: Record<string, unknown> = {
        success: false,
        code: error.code,
        message: error.message,
      };

      if (error instanceof ValidationError && error.details) {
        response.details = error.details;
      }

      res.status(error.statusCode).json(response);
      return;
    }

    if (error instanceof ZodError) {
      const issues = error.issues.map((issue) => ({
        path: issue.path.join('.'),
        message: issue.message,
      }));
      res.status(400).json({
        success: false,
        code: 'VALIDATION_ERROR',
        message: 'Invalid request data',
        details: issues,
      });
      return;
    }

    logger.error('Unhandled error', {
      error: error.message,
      stack: error.stack,
      requestId: res.locals.requestId,
    });

    res.status(500).json({
      success: false,
      code: 'INTERNAL_ERROR',
      message: 'Internal server error',
    });
  };
};
