import { ExceptionFilter, Catch, ArgumentsHost } from '@nestjs/common';
import { Response } from 'express';
import { ApiError } from './api-error';
import { ApiErrorCodes } from './api-error-codes';

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

    let http_code = 400;
    if (exception.code === ApiErrorCodes.ACCESS_DENIED) {
      http_code = 403;
    } else if (exception.code === ApiErrorCodes.ENTITY_NOT_FOUND) {
      http_code = 404;
    }

    response.status(http_code).json({
      code: exception.code,
      message: exception.message,
      payload: exception.payload,
    });
  }
}
