import type { InterfaceType } from "./iface-type.js"

export class PeerBindError extends Error {
  constructor(
    message: string,
    public readonly status: number,
  ) {
    super(message)
    this.name = "PeerBindError"
  }
}

export function truncPeerKey(key: string): string {
  const k = key.trim()
  if (k.length <= 20) return k
  return `${k.slice(0, 8)}…${k.slice(-8)}`
}

export function peerDisplayName(opts: {
  publicKey: string
  name?: string | null
  comment?: string | null
}): string {
  const name = (opts.name ?? "").trim()
  if (name) return name
  const comment = (opts.comment ?? "").trim()
  if (comment) return comment
  return truncPeerKey(opts.publicKey)
}

/** Ether/GRE — пустой ключ. WG — обязательный public-key. */
export function normalizeBindingPeer(
  type: InterfaceType,
  peerPublicKey: string | undefined,
): string {
  const key = (peerPublicKey ?? "").trim()
  if (type === "wg") {
    if (!key) {
      throw new PeerBindError("Для WireGuard укажите пир (public-key)", 400)
    }
    return key
  }
  return ""
}
