import {
  getWishesByTree,
  getMyWishes as getMyWishesMock,
  getWishById,
  createWish as createWishMock,
  deleteWish as deleteWishMock,
  likeWish as likeWishMock,
} from '@/mock/wish'
import type { Wish } from '@/mock/data'
import { request } from './request'

const USE_MOCK = false

/**
 * 许愿树下的公开愿望列表（分页）
 */
export async function fetchTreeWishes(treeId: number, page = 1, pageSize = 20) {
  if (USE_MOCK) return getWishesByTree(treeId, page, pageSize)

  const res = await request<{ records: Wish[]; total: number }>(
    `/mobile/wish/tree/${treeId}?page=${page}&pageSize=${pageSize}`,
  )
  return { list: res.data.records, total: res.data.total }
}

/**
 * 我的愿望列表（分页，基于 token 识别用户）
 */
export async function fetchMyWishes(page = 1, pageSize = 20) {
  if (USE_MOCK) return getMyWishesMock('', page, pageSize)

  const res = await request<{ records: Wish[]; total: number }>(
    `/mobile/wish/my?page=${page}&pageSize=${pageSize}`,
  )
  return { list: res.data.records, total: res.data.total }
}

export async function fetchWishDetail(id: number) {
  if (USE_MOCK) return getWishById(id)

  const res = await request<Wish>(`/mobile/wish/${id}`)
  return res.data
}

/**
 * 创建愿望（用户信息由后端从 token 获取）
 */
export async function submitWish(data: {
  treeId: number
  content: string
  images: string[]
  lng: number
  lat: number
  address: string
  isPublic: boolean
  tags: string[]
  type: number
}) {
  if (USE_MOCK) return createWishMock(data as any)

  const res = await request<Wish>('/mobile/wish/create', {
    method: 'POST',
    body: JSON.stringify(data),
  })
  return res.data
}

export async function removeWish(id: number, userId?: string) {
  if (USE_MOCK) return deleteWishMock(id)

  const res = await request<boolean>(`/mobile/wish/${id}`, {
    method: 'DELETE',
    headers: userId ? { 'X-User-Id': userId } : undefined,
  })
  return res.data
}

export async function toggleLikeWish(id: number) {
  if (USE_MOCK) return likeWishMock(id)

  const res = await request<number>(`/mobile/wish/${id}/like`, { method: 'POST' })
  return res.data
}
