// Consumed by `@bridges/iam/user/adapters/iam-credential-verifier.adapter.ts` to back the
// `ICredentialVerifier` port declared in `@aurora/modules/authentication/domain/ports/`.
import { IamSequelizeUserRepository, IamUserModel } from '@app/iam/user';
import { Injectable } from '@nestjs/common';
import * as bcrypt from 'bcrypt';

@Injectable()
export class IamFindUserByUsernamePasswordService {
  constructor(private readonly repository: IamSequelizeUserRepository) {}

  // Finds an IamUser by joining IamAccount on `username` and verifying the bcrypt password.
  // Returns the model when the account is active AND the password matches; returns null otherwise.
  // Critically, all failure modes (user not found, password mismatch, account inactive) collapse
  // to a single `null` return to prevent username enumeration attacks (RFC 6819 §5.3.4).
  async main(username: string, password: string): Promise<IamUserModel | null> {
    const user = (await this.repository.find({
      queryStatement: {
        include: [
          {
            association: 'account',
            where: {
              username,
            },
          },
        ],
      },
    })) as unknown as IamUserModel | null;

    if (!user) return null;
    if (!user.account?.isActive) return null;
    if (!bcrypt.compareSync(password, user.password)) return null;

    return user;
  }
}
