import apiClient from './client'
import type { Tree, TreeListItem, TreeCreate, TreeUpdate, TreeFilters, TreeShareCreate, TreeShare, TreeVisibilityUpdate, TreeValidationResponse, AIFixTreeRequest, AIFixTreeResponse } from '@/types'

export const treesApi = {
  async list(params?: TreeFilters): Promise<TreeListItem[]> {
    const response = await apiClient.get<TreeListItem[]>('/trees', { params })
    return response.data
  },

  async get(id: string): Promise<Tree> {
    const response = await apiClient.get<Tree>(`/trees/${id}`)
    return response.data
  },

  async create(data: TreeCreate): Promise<Tree> {
    const response = await apiClient.post<Tree>('/trees', data)
    return response.data
  },

  async update(id: string, data: TreeUpdate): Promise<Tree> {
    const response = await apiClient.put<Tree>(`/trees/${id}`, data)
    return response.data
  },

  async delete(id: string): Promise<void> {
    await apiClient.delete(`/trees/${id}`)
  },

  // Legacy categories endpoint (returns string categories)
  async legacyCategories(): Promise<string[]> {
    const response = await apiClient.get<string[]>('/trees/categories')
    return response.data
  },

  async search(query: string, limit?: number): Promise<TreeListItem[]> {
    const response = await apiClient.get<TreeListItem[]>('/trees/search', {
      params: { q: query, limit },
    })
    return response.data
  },

  async fork(id: string, data?: { fork_reason?: string; name?: string }): Promise<Tree> {
    const response = await apiClient.post<Tree>(`/trees/${id}/fork`, data || {})
    return response.data
  },

  // Tree sharing
  async createShare(id: string, data: TreeShareCreate): Promise<TreeShare> {
    const response = await apiClient.post<TreeShare>(`/trees/${id}/share`, data)
    return response.data
  },

  async listShares(id: string): Promise<TreeShare[]> {
    const response = await apiClient.get<TreeShare[]>(`/trees/${id}/shares`)
    return response.data
  },

  async updateVisibility(id: string, data: TreeVisibilityUpdate): Promise<Tree> {
    const response = await apiClient.patch<Tree>(`/trees/${id}/visibility`, data)
    return response.data
  },

  // Tree validation
  async canPublish(id: string): Promise<TreeValidationResponse> {
    const response = await apiClient.post<TreeValidationResponse>(`/trees/${id}/can-publish`)
    return response.data
  },

  // AI auto-fix
  async fixTree(request: AIFixTreeRequest): Promise<AIFixTreeResponse> {
    const response = await apiClient.post<AIFixTreeResponse>('/ai/fix-tree', request)
    return response.data
  },
}

export default treesApi
