import { apiClient } from './apiClient';
import { KnowledgeFile } from '../types';

export const knowledgeBaseService = {
  async getAll(
    authToken: string,
    options: {
      page?: number;
      limit?: number;
      name?: string;
      status?: string;
      groupId?: string;
    } = {}
  ): Promise<{ items: KnowledgeFile[]; total: number; page: number; limit: number }> {
    const queryParams = new URLSearchParams();
    if (options.page) queryParams.append('page', options.page.toString());
    if (options.limit) queryParams.append('limit', options.limit.toString());
    if (options.name) queryParams.append('name', options.name);
    if (options.status) queryParams.append('status', options.status);
    if (options.groupId) queryParams.append('groupId', options.groupId);

    const queryString = queryParams.toString();
    const url = `/knowledge-bases${queryString ? `?${queryString}` : ''}`;

    const response = await apiClient.request(url, {});

    if (!response.ok) {
      throw new Error('Failed to fetch knowledge base files');
    }

    const data = await response.json();
    console.log('Knowledge base API response:', data);

    const items = Array.isArray(data) ? data : (data.items || []);
    const total = Array.isArray(data) ? data.length : (data.total || 0);
    const page = Array.isArray(data) ? 1 : (data.page || 1);
    const limit = Array.isArray(data) ? items.length : (data.limit || 12);

    return {
      items: items.map((item: any) => ({
        id: item.id,
        name: item.originalName,
        originalName: item.originalName,
        type: item.mimetype,
        size: item.size,
        status: item.status,
        groups: item.groups || [],
        createdAt: item.createdAt,
        updatedAt: item.updatedAt,
      })),
      total,
      page,
      limit,
    };
  },

  async getStatuses(ids: string[], authToken: string): Promise<{ id: string, status: KnowledgeFile['status'], updatedAt: string }[]> {
    const response = await apiClient.request('/knowledge-bases/statuses', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify({ ids }),
    });

    if (!response.ok) {
      throw new Error('Failed to fetch knowledge base statuses');
    }

    return response.json();
  },

  async getStats(authToken: string): Promise<{ total: number, uncategorized: number }> {
    const response = await apiClient.request('/knowledge-bases/stats', {
      method: 'GET'
    });

    if (!response.ok) {
      throw new Error('Failed to fetch knowledge base stats');
    }

    return response.json();
  },

  async clearAll(authToken: string): Promise<void> {
    const response = await apiClient.request('/knowledge-bases/clear', {
      method: 'DELETE',
    });

    if (!response.ok) {
      throw new Error('Failed to clear knowledge base');
    }
  },

  async search(query: string, topK: number = 5, authToken: string): Promise<any> {
    const response = await apiClient.request('/knowledge-bases/search', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify({ query, topK }),
    });

    if (!response.ok) {
      throw new Error('Failed to search knowledge base');
    }

    return response.json();
  },

  async deleteFile(fileId: string, authToken: string): Promise<void> {
    const response = await apiClient.request(`/knowledge-bases/${fileId}`, {
      method: 'DELETE',
    });

    if (!response.ok) {
      throw new Error('Failed to delete file');
    }
  },

  async retryFile(fileId: string, authToken: string): Promise<KnowledgeFile> {
    const response = await apiClient.request(`/knowledge-bases/${fileId}/retry`, {
      method: 'POST',
    });

    if (!response.ok) {
      throw new Error('Failed to retry file');
    }

    const item = await response.json();
    return {
      id: item.id,
      name: item.originalName,
      originalName: item.originalName,
      type: item.mimetype,
      size: item.size,
      status: item.status,
      groups: item.groups || [],
      createdAt: item.createdAt,
      updatedAt: item.updatedAt,
    };
  },

  async getFileChunks(fileId: string, authToken: string) {
    const response = await apiClient.request(`/knowledge-bases/${fileId}/chunks`, {});

    if (!response.ok) {
      throw new Error('Failed to get file chunks');
    }

    return response.json();
  },

  getPageImageUrl(fileId: string, pageIndex: number): string {
    return `/api/knowledge-bases/${fileId}/page/${pageIndex}`;
  },
};
