import { useMemo } from "react";
import { checkPasswordStrength } from "@customer-portal/domain/auth";

export interface PasswordChecks {
  minLength: boolean;
  hasUppercase: boolean;
  hasLowercase: boolean;
  hasNumber: boolean;
}

export interface PasswordValidation {
  checks: PasswordChecks;
  strength: number;
  isValid: boolean;
  error: string | undefined;
}

export function usePasswordValidation(password: string): PasswordValidation {
  return useMemo(() => {
    const { requirements, strength, isValid } = checkPasswordStrength(password);

    const byKey = Object.fromEntries(requirements.map(r => [r.key, r.met]));
    const checks: PasswordChecks = {
      minLength: byKey["minLength"] ?? false,
      hasUppercase: byKey["uppercase"] ?? false,
      hasLowercase: byKey["lowercase"] ?? false,
      hasNumber: byKey["number"] ?? false,
    };

    const firstFailing = requirements.find(r => !r.met);
    let error: string | undefined;
    if (password.length === 0) {
      error = "Password is required";
    } else if (firstFailing) {
      error = firstFailing.label;
    }

    return { checks, strength, isValid, error };
  }, [password]);
}
