import apiClient from './client'
import type { Tag, TagListItem, TagCreate, TagAssignment } from '@/types'

export const tagsApi = {
  async list(includeAccount = true): Promise<TagListItem[]> {
    const response = await apiClient.get<TagListItem[]>('/tags', {
      params: { include_account: includeAccount },
    })
    return response.data
  },

  async search(query: string, limit = 10, includeAccount = true): Promise<TagListItem[]> {
    const response = await apiClient.get<TagListItem[]>('/tags/search', {
      params: { q: query, limit, include_account: includeAccount },
    })
    return response.data
  },

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

  async create(data: TagCreate): Promise<Tag> {
    const response = await apiClient.post<Tag>('/tags', data)
    return response.data
  },

  // Tree tag management
  async getTreeTags(treeId: string): Promise<TagListItem[]> {
    const response = await apiClient.get<TagListItem[]>(`/tags/trees/${treeId}`)
    return response.data
  },

  async addTagsToTree(treeId: string, tags: string[]): Promise<TagListItem[]> {
    const response = await apiClient.post<TagListItem[]>(`/tags/trees/${treeId}`, {
      tags,
    } as TagAssignment)
    return response.data
  },

  async replaceTreeTags(treeId: string, tags: string[]): Promise<TagListItem[]> {
    const response = await apiClient.put<TagListItem[]>(`/tags/trees/${treeId}`, {
      tags,
    } as TagAssignment)
    return response.data
  },

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

export default tagsApi
