import "server-only";
import { hash, verify } from "@node-rs/argon2";

// Default algorithm is Argon2id; omit enum to avoid isolatedModules ambient const enum error
const opts = {
  memoryCost: 19_456,
  timeCost: 2,
  parallelism: 1,
} as const;

export async function hashPassword(plain: string): Promise<string> {
  return hash(plain, opts);
}

export async function verifyPassword(plain: string, encoded: string): Promise<boolean> {
  try {
    return await verify(encoded, plain);
  } catch {
    return false;
  }
}

/**
 * Policy for user-chosen passwords. Centralised so the signup, reset, and
 * change-password flows all enforce the same rules. Returns a list of human
 * readable issues; empty means accepted.
 */
export function assessPasswordStrength(password: string): string[] {
  const issues: string[] = [];
  if (password.length < 10) issues.push("Use at least 10 characters.");
  if (password.length > 256) issues.push("Password is too long (max 256 characters).");
  if (!/[A-Z]/.test(password)) issues.push("Include at least one uppercase letter.");
  if (!/[a-z]/.test(password)) issues.push("Include at least one lowercase letter.");
  if (!/[0-9]/.test(password)) issues.push("Include at least one digit.");
  return issues;
}
