/**
 * Basic Auth credential pairs from environment (primary + optional second user).
 */

export type BasicAuthCredentialPair = { user: string; pass: string };

export function getBasicAuthCredentialPairs(): BasicAuthCredentialPair[] {
  const pairs: BasicAuthCredentialPair[] = [];
  const u1 = process.env.BASIC_AUTH_USER?.trim() ?? "";
  const p1 = process.env.BASIC_AUTH_PASSWORD?.trim() ?? "";
  if (u1 && p1) pairs.push({ user: u1, pass: p1 });
  const u2 = process.env.BASIC_AUTH_USER_2?.trim() ?? "";
  const p2 = process.env.BASIC_AUTH_PASSWORD_2?.trim() ?? "";
  if (u2 && p2) pairs.push({ user: u2, pass: p2 });
  return pairs;
}

export function isBasicAuthEnabled(): boolean {
  return getBasicAuthCredentialPairs().length > 0;
}

export function basicAuthMatchesDecodedUserPass(
  user: string,
  pass: string,
): boolean {
  return getBasicAuthCredentialPairs().some(
    (pair) => pair.user === user && pair.pass === pass,
  );
}

/** Returns Basic `user:pass` when the header is valid Base64. */
export function parseBasicAuthCredentials(
  authorizationHeader: string | undefined,
): { user: string; pass: string } | null {
  const authHeader = authorizationHeader ?? "";
  if (!authHeader.startsWith("Basic ")) return null;
  const encoded = authHeader.slice("Basic ".length).trim();
  try {
    const decoded = Buffer.from(encoded, "base64").toString("utf-8");
    const separatorIndex = decoded.indexOf(":");
    if (separatorIndex === -1) return null;
    return {
      user: decoded.slice(0, separatorIndex),
      pass: decoded.slice(separatorIndex + 1),
    };
  } catch {
    return null;
  }
}

/** Returns the Basic username (without password) when the header is valid Base64 `user:pass`. */
export function parseBasicAuthUsername(
  authorizationHeader: string | undefined,
): string | null {
  return parseBasicAuthCredentials(authorizationHeader)?.user ?? null;
}
