import {
  ExceptionFilter,
  Catch,
  ArgumentsHost,
  HttpStatus,
  Logger,
  HttpException,
} from '@nestjs/common';
import { Request, Response } from 'express';

/**
 * 领域异常基类
 */
export class DomainException extends Error {
  constructor(
    message: string,
    public readonly code: string,
    public readonly httpStatus: HttpStatus = HttpStatus.BAD_REQUEST,
  ) {
    super(message);
    this.name = 'DomainException';
  }
}

/**
 * 实体未找到异常
 */
export class EntityNotFoundException extends DomainException {
  constructor(entityName: string, id: string) {
    super(`${entityName} with id ${id} not found`, 'ENTITY_NOT_FOUND', HttpStatus.NOT_FOUND);
    this.name = 'EntityNotFoundException';
  }
}

/**
 * 业务规则违反异常
 */
export class BusinessRuleViolationException extends DomainException {
  constructor(message: string, code: string = 'BUSINESS_RULE_VIOLATION') {
    super(message, code, HttpStatus.UNPROCESSABLE_ENTITY);
    this.name = 'BusinessRuleViolationException';
  }
}

/**
 * 并发冲突异常
 */
export class ConcurrencyException extends DomainException {
  constructor(message: string = 'Concurrency conflict detected') {
    super(message, 'CONCURRENCY_CONFLICT', HttpStatus.CONFLICT);
    this.name = 'ConcurrencyException';
  }
}

@Catch()
export class DomainExceptionFilter implements ExceptionFilter {
  private readonly logger = new Logger(DomainExceptionFilter.name);

  catch(exception: unknown, host: ArgumentsHost) {
    const ctx = host.switchToHttp();
    const response = ctx.getResponse<Response>();
    const request = ctx.getRequest<Request>();

    let status = HttpStatus.INTERNAL_SERVER_ERROR;
    let code = 'INTERNAL_ERROR';
    let message = 'Internal server error';
    let details: any = null;

    if (exception instanceof DomainException) {
      status = exception.httpStatus;
      code = exception.code;
      message = exception.message;
    } else if (exception instanceof HttpException) {
      status = exception.getStatus();
      const exceptionResponse = exception.getResponse();

      if (typeof exceptionResponse === 'object' && exceptionResponse !== null) {
        message = (exceptionResponse as any).message || exception.message;
        code = (exceptionResponse as any).error?.toUpperCase().replace(/ /g, '_') || 'HTTP_ERROR';
        details = (exceptionResponse as any).details;
      } else {
        message = exception.message;
        code = 'HTTP_ERROR';
      }
    } else if (exception instanceof Error) {
      message = exception.message;
      this.logger.error(`Unhandled exception: ${exception.message}`, exception.stack);
    }

    const errorResponse = {
      success: false,
      error: {
        code,
        message: Array.isArray(message) ? message : [message],
        details,
      },
      timestamp: new Date().toISOString(),
      path: request.url,
      method: request.method,
    };

    response.status(status).json(errorResponse);
  }
}
