import { Inject, Injectable } from '@nestjs/common';
import type {
  ListModelsRequest,
  ListModelsResponse,
  ModelsServiceClient,
} from '../gen/apf-ai/models';
import { GrpcMetadataBuilder } from './grpc-metadata.builder';
import { AI_MODELS_GRPC_CLIENT } from './tokens';

/**
 * Wrapper around the generated `ModelsServiceClient` for the unary
 * `ListModels` RPC. Surfaces the active provider + the configured
 * provider catalogue for use by a future admin UI tile or a v1
 * "which models are available" health probe.
 */
@Injectable()
export class ModelsClient {
  constructor(
    @Inject(AI_MODELS_GRPC_CLIENT) private readonly grpc: ModelsServiceClient,
    private readonly metadata: GrpcMetadataBuilder,
  ) {}

  listModels(
    request: ListModelsRequest = {},
    options: { correlationId?: string } = {},
  ): Promise<ListModelsResponse> {
    const metadata = this.metadata.build({ correlationId: options.correlationId });
    return new Promise<ListModelsResponse>((resolve, reject) => {
      this.grpc.listModels(request, metadata, (err, response) => {
        if (err) {
          reject(err);
          return;
        }
        resolve(response);
      });
    });
  }
}
