import {
  CallHandler,
  ExecutionContext,
  Injectable,
  NestInterceptor,
  StreamableFile,
} from "@nestjs/common";
import { Readable } from "stream";
import { Observable } from "rxjs";
import { map } from "rxjs/operators";
import { flatResponseModules } from "../constants/apiModules";

export interface StandardResponse<T> {
  success: true;
  data: T;
  timestamp: string;
}

@Injectable()
export class ResponseTransformInterceptor<T> implements NestInterceptor<
  T,
  StandardResponse<T> | T
> {
  intercept(
    _context: ExecutionContext,
    next: CallHandler<T>,
  ): Observable<StandardResponse<T> | T> {
    return next.handle().pipe(
      map((data) => {
        if (
          data instanceof StreamableFile ||
          data instanceof Buffer ||
          data instanceof Readable
        ) {
          return data;
        }
        const request = _context.switchToHttp().getRequest();
        const path = request.route?.path ?? request.originalUrl ?? "";

        const shouldFlatten = flatResponseModules.some((module) =>
          path.startsWith(module),
        );
  
        if (
          shouldFlatten &&
          data &&
          typeof data === "object" &&
          !Array.isArray(data)
        ) {
          return {
            success: true,
            ...data,
            timestamp: new Date().toISOString(),
          };
        }

        return {
          success: true,
          data,
          timestamp: new Date().toISOString(),
        };
      }),
    );
  }
}
