import { CallHandler, ExecutionContext, Injectable, NestInterceptor } from "@nestjs/common";
import { map } from "rxjs";
import { ApiEnvelope } from "../../contracts";

@Injectable()
export class ResponseTransformInterceptor implements NestInterceptor {
  intercept(context: ExecutionContext, next: CallHandler) {
    const requestId = `req-${Date.now()}-${Math.floor(Math.random() * 1e6)}`;
    return next.handle().pipe(
      map((value) => {
        const envelope = value as ApiEnvelope<unknown>;
        if (
          envelope?.requestId &&
          typeof envelope === "object" &&
          (Object.prototype.hasOwnProperty.call(envelope, "data") ||
            Object.prototype.hasOwnProperty.call(envelope, "error"))
        ) {
          return envelope;
        }
        return {
          data: value,
          requestId,
        };
      })
    );
  }
}
