import {
  Injectable,
  NestInterceptor,
  ExecutionContext,
  CallHandler,
} from '@nestjs/common';
import { Observable } from 'rxjs';
import { map } from 'rxjs/operators';
import { Request } from 'express';
import { Reflector } from '@nestjs/core';
import { GATE_RESPONSE, PAGINATION_RESPONSE } from '../constants';
import { createPaginationResponse } from './utils/pagination-meta.helper';

@Injectable()
export class TransformInterceptor implements NestInterceptor {
  constructor(protected readonly reflector: Reflector) {}
  intercept(context: ExecutionContext, next: CallHandler): Observable<any> {
    const isGate = this.reflector.getAllAndOverride<boolean>(GATE_RESPONSE, [
      context.getHandler(),
      context.getClass(),
    ]);

    if (isGate) return next.handle();

    const isPagination = this.reflector.getAllAndOverride<boolean>(
      PAGINATION_RESPONSE,
      [context.getHandler(), context.getClass()],
    );

    const request = context.switchToHttp().getRequest<Request>();
    const start = request.query.page ?? 1;
    const limit = request.query.limit ?? 10;

    return next.handle().pipe(
      map((data) => {
        return isPagination
          ? createPaginationResponse(data, +start, +limit)
          : { data };
      }),
    );
  }
}
