import { Injectable } from "@nestjs/common";
import { UsersService } from "./users.service.js";
import { JwtService } from "@nestjs/jwt";
import type { UserDocument } from "../schemas/user.schema.js";
import { BcryptService } from "./bcrypt.service.js";

@Injectable()
export class AuthService {
  constructor(
    private usersService: UsersService,
    private jwtService: JwtService,
    private bcryptService: BcryptService
  ) {}

  async validateUser(
    username: string,
    password: string
  ): Promise<UserDocument | null> {
    const user = await this.usersService.findOne(username);

    if (
      user &&
      (await this.bcryptService.comparePasswords(password, user.passwordHash))
    ) {
      return user;
    }

    return null;
  }

  async login(user: UserDocument): Promise<{ auth_token: string }> {
    const payload = {
      sub: user._id,
      username: user.username,
    };

    return {
      auth_token: await this.jwtService.signAsync(payload),
    };
  }
}
