import { CallHandler, ExecutionContext, Injectable, NestInterceptor } from '@nestjs/common';
import { JwtService } from '@nestjs/jwt';
import { Observable, mergeMap } from 'rxjs';
import type { Response } from 'express';
import { attachFedcmCookieFromAuthResult } from '../lib/fedcm-cookie';

@Injectable()
export class FedcmCookieInterceptor implements NestInterceptor {
  constructor(private readonly jwt: JwtService) {}

  intercept(context: ExecutionContext, next: CallHandler): Observable<unknown> {
    const http = context.switchToHttp();
    const response = http.getResponse<Response>();

    return next.handle().pipe(
      mergeMap(async (data) => {
        await attachFedcmCookieFromAuthResult(response, this.jwt, data);
        return data;
      })
    );
  }
}
