import {
  CallHandler,
  ExecutionContext,
  Injectable,
  NestInterceptor,
} from '@nestjs/common';
import { Observable, map } from 'rxjs';
import {
  API_SUCCESS_CODE,
  API_SUCCESS_MESSAGE,
  type ApiResponse,
} from './api-response.type';

@Injectable()
export class ResponseInterceptor<T>
  implements NestInterceptor<T, ApiResponse<T>>
{
  intercept(
    _context: ExecutionContext,
    next: CallHandler<T>,
  ): Observable<ApiResponse<T>> {
    return next.handle().pipe(
      map((data) => ({
        code: API_SUCCESS_CODE,
        data: data ?? null,
        msg: API_SUCCESS_MESSAGE,
      })),
    );
  }
}
