import {
  Injectable,
  NestInterceptor,
  ExecutionContext,
  CallHandler,
  Logger,
  HttpException,
} from '@nestjs/common';
import { Observable, catchError } from 'rxjs';

@Injectable()
export class TransformErrorInterceptor implements NestInterceptor {
  private readonly logger = new Logger(TransformErrorInterceptor.name);
  intercept(context: ExecutionContext, next: CallHandler): Observable<any> {
    // next.handle() is an Observable of the controller's result value
    return next.handle().pipe(
      catchError((error) => {
        const response = error.response || {};
        const { statusCode, message } = response;
        throw new HttpException(
          {
            status: statusCode,
            code: error['code'],
            details: {
              type: 'error',
              message: message,
            },
          },
          statusCode,
        );
      }),
    );
  }
}
