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

@Injectable()
export class ResponseInterceptor implements NestInterceptor {
  constructor() { }

  intercept(context: ExecutionContext, next: CallHandler<Record<string, unknown>>): Observable<unknown> {
    // For REST endpoints, wrap the response
    try {
      const ctx = context.switchToHttp().getResponse<FastifyReply>();
      const statusCode = ctx.statusCode;

      // If statusCode is undefined, skip wrapping
      if (statusCode === undefined) {
        return next.handle();
      }

      return next.handle().pipe(
        map(data => {
          // If data is already wrapped or doesn't need wrapping, return as-is
          if (data && typeof data === 'object' && 'data' in data && 'success' in data) {
 
            return {
              data: data,
              ...('nextCursor' in (data as any) && (data as any).nextCursor != null
                ? { nextCursor: (data as any).nextCursor }
                : {}),
            }
          }

          // Check if this is a paginated result (has both data and meta properties)
          if (data && typeof data === 'object' && 'data' in data && 'meta' in data) {
            return {
              statusCode,
              success: true,
              data: data.data,
              meta: data.meta,
            };
          }

          if (data && 'data' in data) {

            return {
              statusCode,
              success: true,
              data: data.data,
              ...('nextCursor' in data
                ? { nextCursor: (data as any).nextCursor }
                : {}),
            };
          }
          return {
            statusCode,
            success: true,
            data,
          };
        }),
      );
    } catch {
      // If we can't get HTTP context, return data as-is
      return next.handle();
    }
  }
}
