import { KnowledgeGroup, CreateGroupData, UpdateGroupData } from '../types';
import { apiClient } from './apiClient';

export const knowledgeGroupService = {
  // Fetch all groups
  async getGroups(options: { flat?: boolean; page?: number; limit?: number; name?: string } = {}): Promise<any> {
    const queryParams = new URLSearchParams();
    if (options.flat) queryParams.append('flat', 'true');
    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);

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

    const response = await apiClient.request(url, {});
    if (!response.ok) throw new Error('Failed to fetch groups');
    const data = await response.json();

    // If it's an array, it's already in the format we expect (tree or simple list)
    if (Array.isArray(data)) return data;

    // If it's a paginated object, return it as is or handle appropriately
    // The callers of getGroups usually expect an array, but NotebooksView expects a tree.
    // However, NotebookDetailView and others might soon expect pagination.
    return data;
  },

  // Create group
  async createGroup(data: CreateGroupData): Promise<KnowledgeGroup> {
    const { data: group } = await apiClient.post<KnowledgeGroup>('/knowledge-groups', data);
    return group;
  },

  // Update group
  async updateGroup(id: string, data: UpdateGroupData): Promise<KnowledgeGroup> {
    const { data: group } = await apiClient.put<KnowledgeGroup>(`/knowledge-groups/${id}`, data);
    return group;
  },

  // Delete group
  async deleteGroup(id: string): Promise<void> {
    const response = await apiClient.request(`/knowledge-groups/${id}`, {
      method: 'DELETE',
    });
    if (!response.ok) throw new Error('Failed to delete group');
  },

  // Fetch files in group
  async getGroupFiles(id: string): Promise<any[]> {
    const response = await apiClient.request(`/knowledge-groups/${id}/files`, {});
    if (!response.ok) throw new Error('Failed to fetch group files');
    const data = await response.json();
    return data.files;
  },

  
  async addFileToGroups(fileId: string, groupIds: string[]): Promise<void> {
    await apiClient.post(`/knowledge-bases/${fileId}/groups`, { groupIds });
  },

  // Remove file from group
  async removeFileFromGroup(fileId: string, groupId: string): Promise<void> {
    const response = await apiClient.request(`/knowledge-bases/${fileId}/groups/${groupId}`, {
      method: 'DELETE',
    });
    if (!response.ok) throw new Error('Failed to remove file from group');
  },
};