import { CanActivate, ExecutionContext, Injectable, UnauthorizedException } from '@nestjs/common';
import { UserService } from 'src/user/user.service';
import { AuthUserService } from './authUserservice';

@Injectable()
export class AuthUserGuard implements CanActivate {
  constructor(
    private authUserService: AuthUserService,
    private userService: UserService,
  ) {}
  async canActivate(context: ExecutionContext): Promise<boolean> {
    const request = context.switchToHttp().getRequest();
    let { authorization }: any = request.headers;
    if (!authorization) throw new UnauthorizedException('session expired! Please sign In');
    authorization = authorization.split(' ')[1];
    const jwtPayload = await this.authUserService.validateToken(authorization);
    if (!jwtPayload) throw new UnauthorizedException('session expired! Please sign In');

    const user = await this.userService.findOne(jwtPayload.email);
    if (!user) throw new UnauthorizedException('session expired! Please sign In');
    request.user = { ...user };
    return true;
  }
}
