import { Inject, Injectable } from '@nestjs/common';
import type {
  DeleteDocumentRequest,
  DeleteDocumentResponse,
  DocumentSummary,
  GetDocumentRequest,
  IngestDocumentRequest,
  IngestDocumentResponse,
  IngestionServiceClient,
} from '../gen/apf-ai/ingestion';
import { GrpcMetadataBuilder } from './grpc-metadata.builder';
import { AI_INGESTION_GRPC_CLIENT } from './tokens';

/**
 * Wrapper around the generated `IngestionServiceClient`.
 *
 * Unused by the BFF in v1 — apf-ai-service ships a dedicated CLI
 * (`tools/Apf.Ai.Ingest/`) for document ingestion during the POC.
 * The wrapper is in place so the future admin "manage AI corpus"
 * surface lands as one new controller, not as a new module + a new
 * client + a new generated stub binding. The unit tests under
 * `ingestion.client.spec.ts` lock the wire contract today.
 */
@Injectable()
export class IngestionClient {
  constructor(
    @Inject(AI_INGESTION_GRPC_CLIENT) private readonly grpc: IngestionServiceClient,
    private readonly metadata: GrpcMetadataBuilder,
  ) {}

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

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

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