import commonPasswords from "./commonPasswords.json";

// Define the AnalysisResult type
export type AnalysisResult = {
  score: number;
  strength: "very weak" | "weak" | "medium" | "strong";
  metrics: {
    length: number;
    uniqueChars: number;
    hasUpperCase: boolean;
    hasLowerCase: boolean;
    hasNumbers: boolean;
    hasSpecialChars: boolean;
    isCommon: boolean;
  };
};

// Analyze password and return the AnalysisResult type
export function analyzePassword(password: string): AnalysisResult {
  if (!password) {
    throw new Error("Password cannot be empty.");
  }

  const common = (commonPasswords as string[]).includes(password);

  const lengthScore = Math.min(password.length, 20);
  const uniqueChars = new Set(password).size;
  const hasUpperCase = /[A-Z]/.test(password);
  const hasLowerCase = /[a-z]/.test(password);
  const hasNumbers = /\d/.test(password);
  const hasSpecialChars = /[!@#$%^&*(),.?":{}|<>]/.test(password);

  let score = lengthScore;
  if (hasUpperCase) score += 10;
  if (hasLowerCase) score += 10;
  if (hasNumbers) score += 10;
  if (hasSpecialChars) score += 15;

  if (common) {
    score -= 25;
  }

  const strength =
    score >= 75
      ? "strong"
      : score >= 50
      ? "medium"
      : score >= 25
      ? "weak"
      : "very weak";

  return {
    score,
    strength,
    metrics: {
      length: password.length,
      uniqueChars,
      hasUpperCase,
      hasLowerCase,
      hasNumbers,
      hasSpecialChars,
      isCommon: common,
    },
  };
}
