import { HttpException, HttpStatus } from '@nestjs/common';

interface ErrorDetail {
  path: string;
  message: string;
}

class HttpErrorResponse extends HttpException {
  constructor(
    message: string | ErrorDetail[],
    status?: HttpStatus,
    data: any = null,
  ) {
    let responsePayload: any;

    // If message is an array of errors, format as Zod-like structure
    if (Array.isArray(message)) {
      const errors = message;
      const properties: Record<string, { errors: string[] }> = {};

      errors.forEach((error) => {
        if (!properties[error.path]) {
          properties[error.path] = { errors: [] };
        }
        properties[error.path].errors.push(error.message);
      });

      responsePayload = {
        message: {
          errors: errors.map((e) => `${e.message}`),
          properties,
        },
        data: data || null,
        status: status || HttpStatus.BAD_REQUEST,
      };
    } else {
      // Simple message format (keep backward compatibility)
      responsePayload = {
        message: message || 'An error occurred',
        data: data || null,
        status: status || HttpStatus.INTERNAL_SERVER_ERROR,
      };
    }

    super(
      responsePayload,
      status || HttpStatus.INTERNAL_SERVER_ERROR,
    );
  }
}

export default HttpErrorResponse;
