import { Inject, Injectable } from '@nestjs/common';
import type { RagSearchRequest, RagSearchResponse, RagServiceClient } from '../gen/apf-ai/rag';
import { GrpcMetadataBuilder } from './grpc-metadata.builder';
import { AI_RAG_GRPC_CLIENT } from './tokens';

/**
 * Wrapper around the generated `RagServiceClient` for the unary
 * `Search` RPC, per ADR-0024.
 *
 * Promisifies the callback-style gRPC stub and injects the standard
 * metadata. Errors propagate as the underlying `ServiceError` (with
 * `code`, `details`, etc.) so callers can map them to portal-side
 * HTTP statuses without losing the gRPC status code.
 */
@Injectable()
export class RagClient {
  constructor(
    @Inject(AI_RAG_GRPC_CLIENT) private readonly grpc: RagServiceClient,
    private readonly metadata: GrpcMetadataBuilder,
  ) {}

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