import { ArgumentsHost, Catch, HttpException } from '@nestjs/common';
import { BaseWsExceptionFilter, WsException } from '@nestjs/websockets';
import type { Socket } from 'socket.io';
import { LoggerService } from '../../plugins/logger/logger.service';

@Catch()
export class WsExceptionFilter extends BaseWsExceptionFilter {
  public constructor(private readonly logger: LoggerService) {
    super();
  }

  public catch(exception: unknown, host: ArgumentsHost) {
    const ctx = host.switchToWs();
    const client = ctx.getClient<Socket>();
    const errorResponse = {
      type: 'error',
      data: { reason: '未知错误', code: 500 },
    };

    if (exception instanceof WsException) {
      errorResponse.data.reason = exception.message;
      errorResponse.data.code = 400; // WebSocket 异常默认为 400
    } else if (exception instanceof HttpException) {
      errorResponse.data.reason = exception.message;
      errorResponse.data.code = exception.getStatus();
    } else if (exception instanceof Error) {
      errorResponse.data.reason = exception.message;
      this.logger.error(exception, 'WsExceptionFilter');
    } else {
      this.logger.error(exception as any, 'WsExceptionFilter');
    }

    // 发送统一格式的错误消息
    client.emit('message', errorResponse);
  }
}
