import api from '../../../shared/utils/api';

export interface Article {
  id: string;
  title: string;
  content: string;
  summary: string;
  category: string;
  tags: string[];
  source: string;
  isPublished: boolean;
  citationCount: number;
  qualityScore: number;
  createdAt: string;
}

export interface ArticleListResponse {
  items: Article[];
  total: number;
}

export interface CreateArticleParams {
  title: string;
  content: string;
  category: string;
  tags?: string[];
  source?: string;
}

export interface ExtractedTextResponse {
  extractedText: string;
  suggestedTitle: string;
  wordCount: number;
  pageCount?: number;
}

export interface UpdateArticleParams extends Partial<CreateArticleParams> {
  id: string;
}

export const knowledgeApi = {
  getArticles: async (category?: string): Promise<ArticleListResponse> => {
    const params = new URLSearchParams();
    if (category) params.append('category', category);
    const response = await api.get(`/knowledge/articles?${params}`);
    return response.data.data;
  },

  createArticle: async (params: CreateArticleParams): Promise<Article> => {
    const response = await api.post('/knowledge/articles', params);
    return response.data.data;
  },

  updateArticle: async ({ id, ...params }: UpdateArticleParams): Promise<Article> => {
    const response = await api.put(`/knowledge/articles/${id}`, params);
    return response.data.data;
  },

  deleteArticle: async (id: string): Promise<void> => {
    await api.delete(`/knowledge/articles/${id}`);
  },

  publishArticle: async (id: string): Promise<void> => {
    await api.post(`/knowledge/articles/${id}/publish`);
  },

  unpublishArticle: async (id: string): Promise<void> => {
    await api.post(`/knowledge/articles/${id}/unpublish`);
  },

  uploadFile: async (file: File): Promise<ExtractedTextResponse> => {
    const formData = new FormData();
    formData.append('file', file);
    const response = await api.post('/knowledge/articles/upload', formData, {
      headers: { 'Content-Type': 'multipart/form-data' },
      timeout: 120000,
    });
    return response.data.data;
  },
};
