import { mockWishes, type Wish } from './data'

let nextId = 100

export function getWishesByTree(treeId: number, page = 1, pageSize = 20) {
  const list = mockWishes
    .filter((w) => w.treeId === treeId && w.isPublic)
    .sort((a, b) => new Date(b.createdAt).getTime() - new Date(a.createdAt).getTime())

  const start = (page - 1) * pageSize
  return Promise.resolve({
    list: list.slice(start, start + pageSize),
    total: list.length,
  })
}

export function getMyWishes(userId: string, page = 1, pageSize = 20) {
  const list = mockWishes
    .filter((w) => w.userId === userId)
    .sort((a, b) => new Date(b.createdAt).getTime() - new Date(a.createdAt).getTime())

  const start = (page - 1) * pageSize
  return Promise.resolve({
    list: list.slice(start, start + pageSize),
    total: list.length,
  })
}

export function getWishById(id: number) {
  const wish = mockWishes.find((w) => w.id === id)
  return Promise.resolve(wish || null)
}

export function createWish(data: Omit<Wish, 'id' | 'status' | 'likes' | 'createdAt'>) {
  const wish: Wish = {
    ...data,
    id: nextId++,
    likes: 0,
    status: 0,
    createdAt: new Date().toISOString().replace('T', ' ').substring(0, 19),
  }
  mockWishes.unshift(wish)
  return Promise.resolve(wish)
}

export function deleteWish(id: number) {
  const idx = mockWishes.findIndex((w) => w.id === id)
  if (idx > -1) {
    mockWishes.splice(idx, 1)
    return Promise.resolve(true)
  }
  return Promise.resolve(false)
}

export function likeWish(id: number) {
  const wish = mockWishes.find((w) => w.id === id)
  if (wish) {
    wish.likes++
    return Promise.resolve(wish.likes)
  }
  return Promise.resolve(0)
}
