// The account key every credential-store read/write in this app goes
// through — the JS twin of `auth::credential_account_key` in
// crates/cambium-core/src/auth.rs. Read that function's doc for the full
// rationale; the short version is that the CLI and this app share one
// encrypted credential store in one config dir, so a key the two faces spell
// differently means "remember me" prompts anyway, duplicate entries pile up,
// and a logout from one face leaves the other face's copy live.
//
// Format: "<bare host:port>|<@handle>", both parts normalized:
//   * the handle gets exactly one leading "@" (server.py's
//     `_normalize_handle` rule, same as normalizeHandle in ConnectionContext),
//   * the handle and the host are ASCII-lowercased.
//
// Case folding matches the server's own notion of identity — `ORG.find_user`
// (CambiumServer/utilities/store.py) compares `user["username"].lower()`, so @GINA and
// @gina are ONE account and must be one stored credential. Hostnames are
// case-insensitive and the port is digits, so the host folds the same way.
//
// The fold is ASCII-only ON PURPOSE, not `toLowerCase()`: this string has to
// be byte-identical to the one Rust builds, and JS's `toLowerCase`, Rust's
// `to_lowercase` and Python's `.lower()` disagree on non-ASCII mappings
// (final sigma, dotted I). A non-ASCII handle therefore keeps its case in
// both languages — never a mismatch between the faces.
//
// This is deliberately NOT built on normalizeHandle(): that one also feeds
// the live username input in ConnectionsModal, where force-lowercasing what
// the user is typing would be a visible (and separate) UX change.
import { hostFromIp } from './serverPins';

const asciiLower = (value) => String(value ?? '').replace(/[A-Z]/g, (c) => c.toLowerCase());

/** Credential-store account key for a connection-card ip + typed username. */
export function credentialAccountKey(ip, username) {
  const stripped = asciiLower(username).replace(/@/g, '');
  const handle = stripped ? `@${stripped}` : '';
  return `${asciiLower(hostFromIp(ip))}|${handle}`;
}
