import { Injectable } from "@nestjs/common";
import * as argon2 from "argon2";
import { UsersService } from "../users/users.service";
import type { User } from "@jorgecuadros/database";

export type SafeUser = Omit<User, "passwordHash">;

@Injectable()
export class AuthService {
  constructor(private readonly usersService: UsersService) {}

  /**
   * Replaces the old app's `passwd = '$password'` plaintext SQL comparison
   * (src/core/auth.php) with a constant-time hash verification. Returns
   * null on any failure — callers should not distinguish "no such user"
   * from "wrong password" in their response.
   */
  async validateUser(email: string, password: string): Promise<SafeUser | null> {
    const user = await this.usersService.findByEmail(email);
    if (!user || !user.active) {
      return null;
    }

    const passwordMatches = await argon2.verify(user.passwordHash, password);
    if (!passwordMatches) {
      return null;
    }

    const { passwordHash: _passwordHash, ...safeUser } = user;
    return safeUser;
  }

  static async hashPassword(plainTextPassword: string): Promise<string> {
    return argon2.hash(plainTextPassword);
  }
}
