import { Injectable, Scope } from '@nestjs/common';
import { UsersSession } from '../entities/user-sessions.interface';
import { JwtService } from '@nestjs/jwt';
import { JWTToken } from '../..';
import { isTokenNearExpired } from '../utils/jwt.helpers';

@Injectable({ scope: Scope.REQUEST })
export class SessionService {
  private public = false;
  public ignorePrivilegeCondition = false;

  constructor(private readonly jwt: JwtService) {}

  setPublic(value: boolean) {
    this.public = value;
  }

  get isPublic() {
    return this.public;
  }

  get isPrivate() {
    return !this.isPublic;
  }

  createAccessToken(session: UsersSession): string {
    return this.jwt.sign(session);
  }

  verifyToken(token: string): UsersSession & JWTToken {
    return this.jwt.verify<UsersSession & JWTToken>(token);
  }

  refreshToken(token: string): string | undefined {
    const { exp, iat, ...user } = this.verifyToken(token);
    const isNearExp = isTokenNearExpired(exp, iat);
    return isNearExp ? this.createAccessToken(user) : null;
  }
}
