import apiClient from './client'
import type {
  BranchTreeResponse,
  ForkCreateRequest,
  ForkPointResponse,
  BranchSwitchResponse,
  ReviveRequest,
  BranchMessageRequest,
  BranchMessageResponse,
} from '@/types/branching'

export const branchesApi = {
  async getBranches(sessionId: string): Promise<BranchTreeResponse> {
    const response = await apiClient.get<BranchTreeResponse>(
      `/ai-sessions/${sessionId}/branches`
    )
    return response.data
  },

  async createFork(sessionId: string, data: ForkCreateRequest): Promise<ForkPointResponse> {
    const response = await apiClient.post<ForkPointResponse>(
      `/ai-sessions/${sessionId}/branches/fork`,
      data
    )
    return response.data
  },

  async updateBranchStatus(
    sessionId: string,
    branchId: string,
    status: string,
    reason?: string
  ): Promise<void> {
    await apiClient.patch(
      `/ai-sessions/${sessionId}/branches/${branchId}`,
      { status, status_reason: reason }
    )
  },

  async switchBranch(sessionId: string, branchId: string): Promise<BranchSwitchResponse> {
    const response = await apiClient.post<BranchSwitchResponse>(
      `/ai-sessions/${sessionId}/branches/${branchId}/switch`
    )
    return response.data
  },

  async reviveBranch(sessionId: string, branchId: string, data: ReviveRequest): Promise<void> {
    await apiClient.post(
      `/ai-sessions/${sessionId}/branches/${branchId}/revive`,
      data
    )
  },

  async sendBranchMessage(
    sessionId: string,
    branchId: string,
    data: BranchMessageRequest
  ): Promise<BranchMessageResponse> {
    const response = await apiClient.post<BranchMessageResponse>(
      `/ai-sessions/${sessionId}/branches/${branchId}/message`,
      data
    )
    return response.data
  },
}

export default branchesApi
