import {
  Injectable,
  ExecutionContext,
  CanActivate,
  HttpException,
  HttpStatus,
} from '@nestjs/common';
import * as jwt from 'jsonwebtoken';

@Injectable()
export class AuthGuard implements CanActivate {
  // check for logged in user
  async canActivate(context: ExecutionContext): Promise<boolean> {
    // get request
    const request = context.switchToHttp().getRequest();
    // check for authorization header
    if (!request.headers.authorization) {
      return false;
    }

    // validate token
    request.user = await this.validateToken(request.headers.authorization);

    return true;
  }

  // validate token
  async validateToken(auth: string) {
    // check if header contains Bearer
    if (auth.split(' ')[0] !== 'Bearer') {
      throw new HttpException('Invalid token', HttpStatus.FORBIDDEN);
    }
    // get the token
    const token = auth.split(' ')[1];
    try {
      // return token.
      return await jwt.verify(token, process.env.SECRET);
    } catch (err) {
      const message = `Token error: ${err.message || err.name}`;
      throw new HttpException(message, HttpStatus.FORBIDDEN);
    }
  }
}