import { ExceptionFilter, Catch, ArgumentsHost, HttpStatus } from '@nestjs/common';
import { Response } from 'express';
import {
  DomainError, InsufficientBalanceError, WalletFrozenError,
  WalletNotFoundError, DuplicateTransactionError,
} from '@/shared/exceptions/domain.exception';

@Catch(DomainError)
export class DomainExceptionFilter implements ExceptionFilter {
  catch(exception: DomainError, host: ArgumentsHost) {
    const ctx = host.switchToHttp();
    const response = ctx.getResponse<Response>();

    let status = HttpStatus.BAD_REQUEST;
    let code = 'DOMAIN_ERROR';

    if (exception instanceof InsufficientBalanceError) {
      status = HttpStatus.UNPROCESSABLE_ENTITY;
      code = 'INSUFFICIENT_BALANCE';
    } else if (exception instanceof WalletFrozenError) {
      status = HttpStatus.FORBIDDEN;
      code = 'WALLET_FROZEN';
    } else if (exception instanceof WalletNotFoundError) {
      status = HttpStatus.NOT_FOUND;
      code = 'WALLET_NOT_FOUND';
    } else if (exception instanceof DuplicateTransactionError) {
      status = HttpStatus.CONFLICT;
      code = 'DUPLICATE_TRANSACTION';
    }

    response.status(status).json({
      success: false,
      code,
      message: exception.message,
      timestamp: new Date().toISOString(),
    });
  }
}
