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<{ list: Wish[]; total: number }>(
    `/mobile/wish/tree/${treeId}?page=${page}&pageSize=${pageSize}`,
  )
  return { list: res.data.list, total: res.data.total }
}

export async function fetchMyWishes(userId: string, page = 1, pageSize = 20) {
  if (USE_MOCK) return getMyWishesMock(userId, page, pageSize)

  const res = await request<{ list: Wish[]; total: number }>(
    `/mobile/wish/my?page=${page}&pageSize=${pageSize}`,
    { headers: { 'X-User-Id': userId } },
  )
  return { list: res.data.list, 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
}

export async function submitWish(data: Omit<Wish, 'id' | 'status' | 'likes' | 'createdAt'>) {
  if (USE_MOCK) return createWishMock(data)

  const { userId, ...body } = data as any
  const res = await request<Wish>('/mobile/wish/create', {
    method: 'POST',
    body: JSON.stringify(body),
    headers: { 'X-User-Id': userId || 'anonymous' },
  })
  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
}
