import { Injectable, UnauthorizedException } from '@nestjs/common';
import { User, UserService } from 'src/user/user.service';
import { JwtService } from '@nestjs/jwt';

import { compare } from 'bcrypt';
@Injectable()
export class AuthService {
  constructor(
    private readonly userService: UserService,
    private readonly jwtService: JwtService,
  ) {}

  async validateUser(username: string, password: string): Promise<User> {
    const user = await this.userService.findByUsername(username);
    if (user && (await this.compare(password, user.properties.password))) {
      return user;
    }
    throw new UnauthorizedException();
  }

  async signToken(user: User) {
    const { id, email, username } = user.properties;
    return {
      access_token: this.jwtService.sign({
        sub: id,
        email,
        username,
      }),
    };
  }

  async compare(plain: string, hashed: string): Promise<boolean> {
    return await compare(plain, hashed);
  }
}
