import { hash, verify } from "@node-rs/argon2";
import { randomBytes } from "node:crypto";

/**
 * Password hashing — Argon2id.
 *
 * Argon2id is the OWASP-recommended default: it resists both GPU cracking
 * (memory hardness) and side-channel attacks (hybrid data-independent
 * addressing). Parameters follow OWASP's minimum guidance (19 MiB, 2
 * iterations, parallelism 1).
 *
 * The `algorithm` field is written as its numeric id (Argon2id = 2) because the
 * package exposes `Algorithm` as an ambient `const enum`, which TypeScript
 * forbids reading under `isolatedModules`.
 */

const ARGON2ID = 2;

const OPTIONS = {
  algorithm: ARGON2ID,
  memoryCost: 19456, // 19 MiB
  timeCost: 2,
  parallelism: 1,
} as const;

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

export async function verifyPassword(plain: string, digest: string): Promise<boolean> {
  try {
    return await verify(digest, plain, OPTIONS);
  } catch {
    // A malformed/legacy digest must never throw into the request path.
    return false;
  }
}

/**
 * A syntactically valid Argon2id digest of a random value, used to keep the
 * sign-in path's timing uniform when the submitted username does not exist.
 *
 * The obvious shortcut — a hand-written literal such as
 * `$argon2id$v=19$m=19456,t=2,p=1$<salt>$<zeros>` — is worse than doing
 * nothing: `verify` rejects it during decoding and returns in well under a
 * millisecond, while a real account spends ~20 ms hashing. The 3x difference
 * is a reliable oracle for "this username exists". A genuine digest costs the
 * same to verify as any user's, which is the whole point.
 *
 * Built once per process, lazily, so importing this module stays cheap.
 */
let dummyDigest: Promise<string> | null = null;

export function dummyVerifyDigest(): Promise<string> {
  if (!dummyDigest) {
    dummyDigest = hash(randomBytes(32).toString("base64url"), OPTIONS).catch(() => "");
  }
  return dummyDigest;
}

export interface PasswordPolicyResult {
  ok: boolean;
  errors: string[];
}

/**
 * Server-side password policy. Enforced on registration and password change.
 * Deliberately length-biased rather than composition-biased: long passphrases
 * beat `P@ssw0rd!` style rules.
 */
export function checkPasswordPolicy(password: string): PasswordPolicyResult {
  const errors: string[] = [];
  if (password.length < 8) errors.push("Kata sandi minimal 8 karakter.");
  if (password.length > 200) errors.push("Kata sandi maksimal 200 karakter.");
  if (!/[A-Za-z]/.test(password)) errors.push("Kata sandi harus mengandung minimal satu huruf.");
  if (!/[0-9]/.test(password)) errors.push("Kata sandi harus mengandung minimal satu angka.");
  return { ok: errors.length === 0, errors };
}
