import { createHash } from "node:crypto";
import { SEAT_IMPLEMENTER_USER_PREFIX } from "./seat-constants.mjs";

export const SEAT_ID_RE = /^[A-Za-z0-9][A-Za-z0-9._-]*$/;
export const LINUX_USERNAME_RE = /^[a-z][a-z0-9_-]{0,30}$/;
export const MAX_LINUX_USERNAME = 32;

/** Parity vectors shared with seat_implementer_identity.py tests. */
export const IMPLEMENTER_USERNAME_PARITY_VECTORS = [
  ["seat-a", "ods-seat-a"],
  ["seat_x", "ods-seat_x"],
  ["Seat.UPPER", "ods-5ab9a67b99fa6f96"],
  ["a".repeat(40), "ods-e33cdf9c7f7120b9"],
  ["x".repeat(29), "ods-1702245ac78581c3"],
];

export function implementerUsernameForSeat(seatId) {
  if (!SEAT_ID_RE.test(seatId)) {
    throw new Error("invalid seat id");
  }
  const digest = createHash("sha256").update(seatId, "utf8").digest("hex").slice(0, 16);
  const lowered = `${SEAT_IMPLEMENTER_USER_PREFIX}${seatId.toLowerCase()}`;
  if (seatId !== seatId.toLowerCase() || seatId.includes(".") || lowered.length > MAX_LINUX_USERNAME) {
    return `${SEAT_IMPLEMENTER_USER_PREFIX}${digest}`;
  }
  const candidate = lowered;
  if (LINUX_USERNAME_RE.test(candidate)) return candidate;
  return `${SEAT_IMPLEMENTER_USER_PREFIX}${digest}`;
}
