import { useMemo } from "react";

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

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

export function validatePasswordRules(password: string): string | undefined {
  if (!password) return "Password is required";
  if (password.length < 8) return "Password must be at least 8 characters";
  if (!/[A-Z]/.test(password)) return "Password must contain an uppercase letter";
  if (!/[a-z]/.test(password)) return "Password must contain a lowercase letter";
  if (!/[0-9]/.test(password)) return "Password must contain a number";
  return undefined;
}

export function usePasswordValidation(password: string): PasswordValidation {
  return useMemo(() => {
    const checks: PasswordChecks = {
      minLength: password.length >= 8,
      hasUppercase: /[A-Z]/.test(password),
      hasLowercase: /[a-z]/.test(password),
      hasNumber: /[0-9]/.test(password),
    };

    const isValid =
      checks.minLength && checks.hasUppercase && checks.hasLowercase && checks.hasNumber;
    const error = validatePasswordRules(password);

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