import { CallHandler, ExecutionContext, Injectable, NestInterceptor } from '@nestjs/common';
import { Request } from 'express';
import { map, Observable } from 'rxjs';
import { PublicApiCryptoService } from '../crypto/public-api-crypto.service';

type PublicApiRequest = Request & { publicApiEncrypted?: boolean };

@Injectable()
export class EncryptedResponseInterceptor implements NestInterceptor {
  constructor(private readonly crypto: PublicApiCryptoService) {}

  intercept(context: ExecutionContext, next: CallHandler): Observable<unknown> {
    const request = context.switchToHttp().getRequest<PublicApiRequest>();
    return next.handle().pipe(
      map((value: unknown) => {
        if (!request.publicApiEncrypted) return value;
        return this.crypto.encrypt(value);
      }),
    );
  }
}
