import {
  CanActivate,
  ExecutionContext,
  HttpException,
  HttpStatus,
  Injectable,
  UnauthorizedException,
} from '@nestjs/common';
import { JwtService } from '@nestjs/jwt';
import { AuthService } from './auth.service';
import { Reflector } from '@nestjs/core';
// import { ModelService } from 'src/model/model.service';
import { ModelService } from '../model/model.service';
import { ConfigService } from '@nestjs/config';
import { Console } from 'console';
import { log } from 'util';

@Injectable()
export class AuthGuard implements CanActivate {
  private admin_scope;
  private vendor_scope;

  constructor(
    private jwtservice: JwtService,
    private authService: AuthService,
    private readonly Model: ModelService,
    private Reflector: Reflector,
    private ConfigService: ConfigService
  ) {
    this.admin_scope = this.ConfigService.get<string>('ADMIN_SCOPE');
    this.vendor_scope = this.ConfigService.get<string>('VENDOR_SCOPE');

  }

  async canActivate(context: ExecutionContext): Promise<boolean> {
    const request = context.switchToHttp().getRequest();

    if (!request.headers.authorization) {
      throw new UnauthorizedException();
    }
    const token = request.headers.authorization.split(' ')[1];

    const api_path = request.originalUrl;
    console.log('api_path......', api_path);

    if (!token) {
      throw new HttpException('token not received', HttpStatus.UNAUTHORIZED);
    } else {
      try {
        const payload = await this.jwtservice.verifyAsync(token);
        // console.log("payload",payload);

        let { scope } = payload;
        // console.log("scope",scope);
        
        if (scope == this.admin_scope) {
          let data: any = await this.authService.verifyToken(payload);
          if (data) {
            let user_data = await this.authService.admin_check(
              payload,
              api_path
            );
            // console.log("user_data",user_data);
            
            request.user_data = user_data;
            return request;
          } else {
            throw new HttpException('admin not found', HttpStatus.UNAUTHORIZED);
          }
        } else if (scope == this.vendor_scope) {
          let data: any = await this.authService.verifyToken(payload);
          if (data) {
            let user_data = await this.authService.vendor_check(payload);
            request.user_data = user_data;
            return request.user_data;
          } else {
            throw new HttpException('admin not found', HttpStatus.UNAUTHORIZED);
          }
        } else {
          throw new UnauthorizedException()
        }
      } catch (err) {
        throw err;
      }
    }

  }
}
