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

export const knowledgeBaseService = {
  async getAll(authToken: string): Promise<KnowledgeFile[]> {
    const response = await apiClient.request('/knowledge-bases', {});

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

    const data = await response.json();

    // バックエンドエンティティをフロントエンドの KnowledgeFile にマッピング
    return data.map((item: any) => {
      return {
        id: item.id,
        name: item.originalName,
        type: item.mimetype,
        size: item.size,
        uploadDate: new Date(item.createdAt).getTime(),
        status: item.status, // Pass raw status from backend
        content: '', // Frontend doesn't need content
        groups: item.groups || [], // Add group info
        indexingConfig: {
          chunkSize: item.chunkSize || 1000,
          chunkOverlap: item.chunkOverlap || 200,
          embeddingModelId: item.embeddingModelId || ''
        }
      };
    });
  },

  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,
      type: item.mimetype,
      size: item.size,
      uploadDate: new Date(item.createdAt).getTime(),
      status: item.status,
      content: '',
      groups: item.groups || [],
      indexingConfig: {
        chunkSize: item.chunkSize || 1000,
        chunkOverlap: item.chunkOverlap || 200,
        embeddingModelId: item.embeddingModelId || ''
      }
    };
  },

  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}`;
  },
};
