import { CallHandler, ExecutionContext, Injectable, NestInterceptor } from '@nestjs/common';
import { Observable } from 'rxjs';
import { map } from 'rxjs/operators';

@Injectable()
export class ResponseTransformInterceptor<T> implements NestInterceptor<T, any> {
  intercept(ctx: ExecutionContext, next: CallHandler<T>): Observable<any> {
    // Only wrap HTTP responses. This interceptor is global, so it also runs for RabbitMQ
    // message handlers (golevelup uses Nest's context system) — there, wrapping the return
    // value would corrupt the handler's contract (e.g. a returned Nack would be swallowed,
    // dropping a message instead of dead-lettering it). Let non-HTTP returns pass through.
    if (ctx.getType() !== 'http') {
      return next.handle();
    }
    return next.handle().pipe(
      map((data) => ({ success: true, data, timestamp: new Date().toISOString() })),
    );
  }
}
