import { Inject, Injectable, Request, Scope } from '@nestjs/common';
import { UsersSession } from '../entities/user-sessions.interface';
import { REQUEST } from '@nestjs/core';
import { SessionService } from '../services/session.service';

@Injectable({ scope: Scope.REQUEST })
export class UserProvider {
  constructor(
    @Inject(REQUEST) private readonly request: Request,
    private readonly session: SessionService,
  ) {}
  get user(): UsersSession {
    /**
     * There is no Token validation here
     * Because, the token should be available and active here
     *
     * If this function throw an error
     * rather you trying to call user from function that use `@Unprotected` decorator
     * or you forget to set scope to `Scope.REQUEST` from app.module.
     *
     * Please check the token validation at JWTGuard (core/domain/jwt.guard.ts)
     */
    const [, token] = this.request.headers['authorization'].split(' ');
    return this.session.verifyToken(token);
  }

  get token(): string {
    const [, token] = this.request.headers['authorization'].split(' ');
    return token;
  }
}
