import { isIP } from "node:net";

export type ServerEnv = Readonly<Record<string, string | undefined>>;

export interface ServerBinding {
  readonly host: string;
  readonly port: number;
}

const HOSTNAME = /^(?=.{1,253}$)(?:[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)(?:\.(?:[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?))*\.?$/;

/** Read and validate the address passed directly to Fastify/Node listen(). */
export function readServerBinding(env: ServerEnv = process.env): ServerBinding {
  const host = env["HOST"]?.trim() || "127.0.0.1";
  if (isIP(host) === 0 && !HOSTNAME.test(host)) {
    throw new Error("HOST must be a hostname or IP address");
  }

  const rawPort = env["PORT"]?.trim() || "8788";
  const port = Number(rawPort);
  if (!Number.isInteger(port) || port < 1 || port > 65_535) {
    throw new Error("PORT must be an integer between 1 and 65535");
  }

  return { host, port };
}
