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

@Injectable()
export class ResponseEnvelopeInterceptor implements NestInterceptor {
  intercept(context: ExecutionContext, next: CallHandler): Observable<unknown> {
    const http = context.switchToHttp();
    const response = http.getResponse<{ statusCode?: number }>();

    return next.handle().pipe(
      map((data) => ({
        data,
        meta: {
          statusCode: response.statusCode ?? 200,
          timestamp: new Date().toISOString(),
        },
      })),
    );
  }
}
