/**
 * Validate the env vars that drive the BFF's gRPC client to
 * `apf-ai-service`, per ADR-0024.
 *
 * Three knobs, all required at module-init time of `AiClientModule`:
 *
 *   - `AI_SERVICE_GRPC_ENDPOINT` — `host:port` reachable from the
 *     BFF. `apf-ai-service:8080` in the dev Compose network;
 *     a service DNS name + 443 in prod behind an edge proxy that
 *     terminates the public TLS and forwards h2 internally.
 *   - `AI_SERVICE_CLIENT_ID` — deployment slug propagated as the
 *     `x-client-id` gRPC metadata on every call (per
 *     `apf-ai-service/docs/contract.md`). Naming convention:
 *     `apf-portal-<env>` (`apf-portal-dev`, `apf-portal-preprod`,
 *     `apf-portal-prod`).
 *   - `AI_SERVICE_GRPC_TLS` — `'true'` to dial with TLS credentials
 *     against a CA-signed cert (default for non-dev), `'false'` for
 *     h2c against the Compose network in dev. Any other value is
 *     rejected to keep the cleartext-vs-TLS toggle explicit.
 *
 * Following the same family as `assertLogUserIdSalt()` and the
 * other config validators under `apps/portal-bff/src/config/`,
 * per ADR-0018 §"BFF env-var loading" — small, per-key, run at
 * bootstrap, throw with an actionable message on misconfiguration.
 */

export interface AiServiceConfig {
  readonly endpoint: string;
  readonly clientId: string;
  readonly useTls: boolean;
}

const ENDPOINT_PATTERN = /^[a-z0-9.-]+:[0-9]{2,5}$/i;
const CLIENT_ID_PATTERN = /^[a-z0-9-]+$/;

export function assertAiServiceConfig(): AiServiceConfig {
  const endpoint = process.env['AI_SERVICE_GRPC_ENDPOINT'];
  if (!endpoint || endpoint === '') {
    throw new Error(
      `AI_SERVICE_GRPC_ENDPOINT is not set. Expected "host:port" reachable from the BFF, ` +
        `e.g. "apf-ai-service:8080" in dev Compose or "apf-ai.internal:443" in prod.`,
    );
  }
  if (!ENDPOINT_PATTERN.test(endpoint)) {
    throw new Error(
      `AI_SERVICE_GRPC_ENDPOINT must match "host:port" (got: ${JSON.stringify(endpoint)}). ` +
        `Hostname uses a-z 0-9 . - characters; port is 2-5 digits.`,
    );
  }

  const clientId = process.env['AI_SERVICE_CLIENT_ID'];
  if (!clientId || clientId === '') {
    throw new Error(
      `AI_SERVICE_CLIENT_ID is not set. Use a deployment slug like ` +
        `"apf-portal-dev" / "apf-portal-preprod" / "apf-portal-prod"; ` +
        `propagated as the x-client-id gRPC metadata on every call.`,
    );
  }
  if (!CLIENT_ID_PATTERN.test(clientId)) {
    throw new Error(
      `AI_SERVICE_CLIENT_ID must be a lowercase kebab-case slug ` +
        `(got: ${JSON.stringify(clientId)}). Pattern: ^[a-z0-9-]+$.`,
    );
  }

  const tlsRaw = process.env['AI_SERVICE_GRPC_TLS'] ?? 'true';
  if (tlsRaw !== 'true' && tlsRaw !== 'false') {
    throw new Error(
      `AI_SERVICE_GRPC_TLS must be "true" or "false" (got: ${JSON.stringify(tlsRaw)}). ` +
        `Default in prod is "true"; the dev Compose stack sets it to "false" for h2c.`,
    );
  }

  return {
    endpoint,
    clientId,
    useTls: tlsRaw === 'true',
  };
}
