import client from '../client';

// === Types ===

export interface KnowledgeBase {
  id: string;
  tenant_id: string;
  name: string;
  kb_type: string;
  description: string | null;
  icon: string | null;
  chunk_strategy: Record<string, unknown>;
  intent_keywords: Record<string, unknown>;
  embedding_model: string | null;
  is_enabled: boolean;
  document_count: number;
  chunk_count: number;
  created_at: string;
  updated_at: string;
}

export interface KnowledgeDocument {
  id: string;
  tenant_id: string;
  knowledge_base_id: string;
  title: string;
  doc_type: string;
  source_type: string;
  source_url: string | null;
  file_name: string | null;
  file_size: number | null;
  file_mime_type: string | null;
  content: string | null;
  status: string;
  chunk_count: number;
  embedded_count: number;
  error_message: string | null;
  processing_started_at: string | null;
  processing_completed_at: string | null;
  created_at: string;
  updated_at: string;
}

export interface SearchHit {
  chunk_id: string;
  document_id: string;
  chunk_index: number;
  content: string;
  doc_title: string;
  similarity: number;
  metadata: Record<string, unknown>;
}

export interface CreateKnowledgeBaseReq {
  name: string;
  kb_type: string;
  description?: string;
  icon?: string;
  chunk_strategy?: Record<string, unknown>;
  intent_keywords?: Record<string, unknown>;
  embedding_model?: string;
  is_enabled?: boolean;
}

export interface UpdateKnowledgeBaseReq {
  name?: string;
  kb_type?: string;
  description?: string;
  icon?: string;
  chunk_strategy?: Record<string, unknown>;
  intent_keywords?: Record<string, unknown>;
  embedding_model?: string;
  is_enabled?: boolean;
}

export interface CreateDocumentReq {
  kb_id: string;
  title: string;
  doc_type?: string;
  source_type?: string;
  source_url?: string;
  content?: string;
}

// === API ===

export const knowledgeV2Api = {
  // Knowledge Bases
  listKnowledgeBases: async (params?: {
    kb_type?: string;
    is_enabled?: boolean;
    page?: number;
    page_size?: number;
  }) => {
    const resp = await client.get('/ai/knowledge-bases', { params });
    return resp.data.data as {
      data: KnowledgeBase[];
      total: number;
      page: number;
      page_size: number;
    };
  },

  getKnowledgeBase: async (id: string) => {
    const resp = await client.get(`/ai/knowledge-bases/${id}`);
    return resp.data.data as KnowledgeBase;
  },

  createKnowledgeBase: async (data: CreateKnowledgeBaseReq) => {
    const resp = await client.post('/ai/knowledge-bases', data);
    return resp.data.data as { id: string };
  },

  updateKnowledgeBase: async (id: string, data: UpdateKnowledgeBaseReq) => {
    const resp = await client.put(`/ai/knowledge-bases/${id}`, data);
    return resp.data.data as { id: string };
  },

  deleteKnowledgeBase: async (id: string) => {
    const resp = await client.delete(`/ai/knowledge-bases/${id}`);
    return resp.data.data as { id: string };
  },

  // Documents
  listDocuments: async (
    kbId: string,
    params?: { status?: string; page?: number; page_size?: number },
  ) => {
    const resp = await client.get(
      `/ai/knowledge-bases/${kbId}/documents`,
      { params },
    );
    return resp.data.data as {
      data: KnowledgeDocument[];
      total: number;
      page: number;
      page_size: number;
    };
  },

  getDocument: async (id: string) => {
    const resp = await client.get(`/ai/documents/${id}`);
    return resp.data.data as KnowledgeDocument;
  },

  createManualDocument: async (data: CreateDocumentReq) => {
    const resp = await client.post('/ai/documents/manual', data);
    return resp.data.data as { id: string };
  },

  uploadDocument: async (
    kbId: string,
    file: File,
    title?: string,
  ) => {
    const formData = new FormData();
    formData.append('kb_id', kbId);
    formData.append('file', file);
    if (title) {
      formData.append('title', title);
    }
    const resp = await client.post('/ai/documents/upload', formData, {
      headers: { 'Content-Type': 'multipart/form-data' },
    });
    return resp.data.data as { id: string };
  },

  deleteDocument: async (kbId: string, id: string) => {
    const resp = await client.delete(
      `/ai/knowledge-bases/${kbId}/documents/${id}`,
    );
    return resp.data.data as { id: string };
  },

  // Hit Test
  hitTest: async (kbId: string, query: string, topK?: number) => {
    const resp = await client.post('/ai/documents/hit-test', {
      kb_id: kbId,
      query,
      top_k: topK,
    });
    return resp.data.data as {
      query: string;
      total: number;
      hits: SearchHit[];
    };
  },
};
