import {
  CanActivate,
  ExecutionContext,
  HttpException,
  HttpStatus,
  Injectable,
} from '@nestjs/common';
import { ConfigService } from '@nestjs/config';
import { Request } from 'express';
import { getPublicKey } from '../../../common/jwt/jwt';
import { makeErrorResponse } from '../../error/makeErrorResponse';
import { retrieveAuthorizationToken } from '../../http/helper';
import { isVerifyError, verify } from '../../jwt';
import { AccessToken } from '../../token';

@Injectable()
export class AuthGuard implements CanActivate {
  constructor(private readonly configService: ConfigService) {}
  canActivate(context: ExecutionContext): boolean | Promise<boolean> {
    const pubkey = getPublicKey(this.configService);
    const req = context.switchToHttp().getRequest<Request>();

    const token = retrieveAuthorizationToken(req);
    if (!token) {
      throw new HttpException(
        makeErrorResponse('E000107'),
        HttpStatus.UNAUTHORIZED,
      );
    }
    const payload = verify<AccessToken>(token, pubkey);
    if (isVerifyError(payload)) {
      throw new HttpException(
        makeErrorResponse('E000101'),
        HttpStatus.UNAUTHORIZED,
      );
    }
    return true;
  }
}
