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

export const knowledgeGroupService = {
  // すべてのグループを取得
  async getGroups(): Promise<KnowledgeGroup[]> {
    const response = await apiClient.request('/knowledge-groups', {});
    if (!response.ok) throw new Error('Failed to fetch groups');
    return response.json();
  },

  // グループを作成
  async createGroup(data: CreateGroupData): Promise<KnowledgeGroup> {
    const { data: group } = await apiClient.post<KnowledgeGroup>('/knowledge-groups', data);
    return group;
  },

  // グループを更新
  async updateGroup(id: string, data: UpdateGroupData): Promise<KnowledgeGroup> {
    const { data: group } = await apiClient.put<KnowledgeGroup>(`/knowledge-groups/${id}`, data);
    return 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');
  },

  // グループ内のファイルを取得
  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 });
  },

  // グループからファイルを削除
  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');
  },
};