import { http } from './client'
import type { Bookmark, CreateBookmarkRequest, UpdateBookmarkRequest, VisibilityType, Folder } from '@/types'

export const bookmarkApi = {
  /**
   * 获取书签列表
   */
  async getBookmarks(tag?: string, folderId?: string) {
    const params: Record<string, string> = {}
    if (tag) params.tag = tag
    if (folderId) params.folderId = folderId
    return http.get<Bookmark[]>('/bookmarks', { params: Object.keys(params).length ? params : undefined })
  },

  /**
   * 搜索书签
   */
  async searchBookmarks(keyword: string) {
    return http.get<Bookmark[]>('/bookmarks/search', { params: { keyword } })
  },

  /**
   * 获取书签详情
   */
  async getBookmark(id: string) {
    return http.get<Bookmark>(`/bookmarks/${id}`)
  },

  /**
   * 创建书签
   */
  async createBookmark(data: CreateBookmarkRequest) {
    return http.post<Bookmark>('/bookmarks', data)
  },

  /**
   * 更新书签
   */
  async updateBookmark(id: string, data: UpdateBookmarkRequest) {
    return http.put<Bookmark>(`/bookmarks/${id}`, data)
  },

  /**
   * 删除书签
   */
  async deleteBookmark(id: string) {
    return http.delete(`/bookmarks/${id}`)
  },

  /**
   * 批量删除书签
   */
  async batchDeleteBookmarks(ids: string[]) {
    return http.post<number>('/bookmarks/batch/delete', ids)
  },

  /**
   * 设置可见性
   */
  async setVisibility(id: string, visibility: VisibilityType, allowedDevices?: string[]) {
    return http.put(`/bookmarks/${id}/visibility`, { visibility, allowedDevices })
  },

  /**
   * 记录访问
   */
  async recordVisit(id: string) {
    return http.post(`/bookmarks/${id}/visit`)
  },

  /**
   * 更新排序
   */
  async updateOrder(id: string, order: number) {
    return http.put(`/bookmarks/${id}/order`, { order })
  },

  /**
   * 检查 URL 是否存在
   */
  async checkUrl(url: string) {
    return http.get<boolean>('/bookmarks/check-url', { params: { url } })
  },

  /**
   * 导入书签
   */
  async importBookmarks(bookmarks: CreateBookmarkRequest[]) {
    return http.post<number>('/bookmarks/import', bookmarks)
  },

  /**
   * 导出书签
   */
  async exportBookmarks() {
    return http.get<Bookmark[]>('/bookmarks/export')
  },

  /**
   * 获取文件夹列表
   */
  async getFolders() {
    return http.get<Folder[]>('/folders')
  },

  /**
   * 创建文件夹
   */
  async createFolder(data: { name: string; parentId?: string; icon?: string }) {
    return http.post<Folder>('/folders', data)
  },

  /**
   * 更新文件夹
   */
  async updateFolder(id: string, data: { name?: string; icon?: string; order?: number }) {
    return http.put<Folder>(`/folders/${id}`, data)
  },

  /**
   * 删除文件夹
   */
  async deleteFolder(id: string) {
    return http.delete(`/folders/${id}`)
  },

  /**
   * 移动书签到文件夹
   */
  async moveBookmarkToFolder(bookmarkId: string, folderId: string | null) {
    return http.put(`/bookmarks/${bookmarkId}/folder`, { folderId })
  }
}

