/**
 * `GET /v1/models` — OpenAI-shaped list of configured backends.
 *
 * Returns one entry per `gateway.backends[]` with `id` set to the backend
 * id (which is also what `x-aao-backend-id` and `x-litellm-model-id` will
 * carry in responses). Clients hit this endpoint to discover which model
 * names they may request, and `/api/workers/:id/backends` (the Settings
 * "physical backends" panel) reads it to list the GPUs behind a proxy
 * worker — so it stays backend-id-shaped, NOT role-shaped.
 *
 * Role-based routing (2026-06-09) lives entirely in the router + the worker
 * (which sends a role as the routing key). The over-concentration bug was
 * fixed worker-side by dropping model auto-select in gateway mode, so this
 * endpoint did not need to change. A client may still request a role: the
 * router's role-match arm handles it even though roles aren't advertised here.
 *
 * Auth required: the response surfaces backend ids which could otherwise
 * be enumerated by an unauthenticated probe.
 */
import type { Request, Response } from 'express';
import type { GatewayBackendConfig } from './config.js';

export interface ModelsEndpointDeps {
  getBackends: () => GatewayBackendConfig[];
}

export interface OpenAIModelEntry {
  id: string;
  object: 'model';
  owned_by: 'aao-gateway';
}

export interface OpenAIModelsResponse {
  object: 'list';
  data: OpenAIModelEntry[];
}

export function buildModelsResponse(backends: GatewayBackendConfig[]): OpenAIModelsResponse {
  const data: OpenAIModelEntry[] = backends.map(b => ({
    id: b.id,
    object: 'model',
    owned_by: 'aao-gateway',
  }));
  return { object: 'list', data };
}

export function buildModelsHandler(deps: ModelsEndpointDeps) {
  return function modelsHandler(_req: Request, res: Response): void {
    res.json(buildModelsResponse(deps.getBackends()));
  };
}
