import client from '../client';

/* ── Types ── */

export interface EmbeddingDoc {
  id: string;
  metadata: string;
}

export interface EmbeddingListResult {
  total: number;
  offset: number;
  limit: number;
  documents: EmbeddingDoc[];
}

export interface EmbedUploadResult {
  ok: boolean;
  message: string;
  chunks: number;
  filename?: string;
  url?: string;
}

export interface PurgeResult {
  ok: boolean;
  deleted: number;
  table: string;
  tenancy: string;
}

export interface ConsultResult {
  answer: string;
  documents: {
    content: string;
    source: string;
    distance: number;
    metadata: string;
  }[];
  total: number;
}

/* ── API ── */

export const embeddingsApi = {
  /** List embeddings for a given ADB config + optional table */
  list: (vid: string, tableName?: string, limit = 50, offset = 0) => {
    const params = new URLSearchParams();
    if (tableName) params.set('table_name', tableName);
    params.set('limit', String(limit));
    params.set('offset', String(offset));
    return client.get(`/embeddings/${vid}/list?${params}`) as unknown as Promise<EmbeddingListResult>;
  },

  /** Delete a single embedding document */
  remove: (vid: string, docId: string, tableName?: string) => {
    const qs = tableName ? `?table_name=${encodeURIComponent(tableName)}` : '';
    return client.delete(`/embeddings/${vid}/${docId}${qs}`) as unknown as Promise<{ ok: boolean }>;
  },

  /** Upload a file to generate embeddings */
  uploadFile: (adbConfigId: string, tableName: string, file: File) => {
    const fd = new FormData();
    fd.append('adb_config_id', adbConfigId);
    fd.append('table_name', tableName);
    fd.append('file', file);
    return client.post('/embeddings/upload', fd, {
      headers: { 'Content-Type': 'multipart/form-data' },
    }) as unknown as Promise<EmbedUploadResult>;
  },

  /** Import a URL to generate embeddings */
  uploadUrl: (adbConfigId: string, tableName: string, url: string) => {
    const fd = new FormData();
    fd.append('adb_config_id', adbConfigId);
    fd.append('table_name', tableName);
    fd.append('url', url);
    return client.post('/embeddings/upload-url', fd, {
      headers: { 'Content-Type': 'multipart/form-data' },
    }) as unknown as Promise<EmbedUploadResult>;
  },

  /** Purge embeddings from a table (optionally filtered by tenancy) */
  purge: (vid: string, tableName: string, tenancy?: string) =>
    client.post(`/embeddings/${vid}/purge`, {
      table_name: tableName,
      tenancy: tenancy || '',
    }) as unknown as Promise<PurgeResult>,

  /** Consult embeddings with a question */
  consult: (query: string, tableName?: string, topK = 10) =>
    client.post('/embeddings/consult', {
      query,
      table_name: tableName || '',
      top_k: topK,
    }) as unknown as Promise<ConsultResult>,
};
