import {
  Injectable,
  NestInterceptor,
  ExecutionContext,
  CallHandler,
  Scope,
} from '@nestjs/common';
import { Observable } from 'rxjs';
import { SessionService } from '../..';
import { Response, Request } from 'express';

@Injectable({ scope: Scope.REQUEST })
export class RefreshTokenInterceptor implements NestInterceptor {
  constructor(protected readonly session: SessionService) {}
  intercept(context: ExecutionContext, next: CallHandler): Observable<any> {
    const request = context.switchToHttp().getRequest<Request>();
    const response = context.switchToHttp().getResponse<Response>();
    const authorization = request.headers['authorization'];

    if (authorization) {
      const [, token] = authorization.split(' ');
      const refreshToken = this.session.refreshToken(token);
      if (refreshToken) {
        response.setHeader('ex-refresh-token', refreshToken);
        response.setHeader('Access-Control-Expose-Headers', 'ex-refresh-token');
      }
    }

    return next.handle();
  }
}
