import { get, post } from '../utils/http.js'

const WORLD_CUP_API_PREFIX = '/activity/worldcup'

const logWorldCupApiError = (message, error) => {
  console.error(message, error)
  console.error('error:' + (error.response?.errorMsg || error.errorMsg || error.message || ''))
}

// 获取世界杯比赛列表：tab 为 0 时返回进行中/可投注，tab 为 1 时返回已结束。
export const apiPostWorldCupMatchList = async (data) => {
  try {
    const response = await post(`${WORLD_CUP_API_PREFIX}/match/list`, data)
    return response
  } catch (error) {
    logWorldCupApiError('Failed to get world cup match list:', error)
    throw error
  }
}

// 提交世界杯比赛押注：betOption 为 1 主胜、2 平局、3 客胜。
export const apiPostWorldCupBet = async (data) => {
  try {
    const response = await post(`${WORLD_CUP_API_PREFIX}/bet`, {
      ...data,
      matchId: data?.matchId == null ? '' : String(data.matchId),
    })
    return response
  } catch (error) {
    logWorldCupApiError('Failed to submit world cup bet:', error)
    throw error
  }
}

// 获取我的世界杯竞猜记录：matchId 为空时查询全部比赛记录。
export const apiPostWorldCupMyBetList = async (data) => {
  try {
    const response = await post(`${WORLD_CUP_API_PREFIX}/my/bet/list`, {
      ...data,
      matchId: data?.matchId == null || data.matchId === '' ? data?.matchId : String(data.matchId),
    })
    return response
  } catch (error) {
    logWorldCupApiError('Failed to get world cup my bet list:', error)
    throw error
  }
}

// 获取世界杯排行榜：接口没有业务参数，POST 请求仍传空对象。
export const apiPostWorldCupRankList = async () => {
  try {
    const response = await post(`${WORLD_CUP_API_PREFIX}/rank/list`, {})
    return response
  } catch (error) {
    logWorldCupApiError('Failed to get world cup rank list:', error)
    throw error
  }
}

// 获取世界杯比赛详情，同时返回当前用户本场竞猜记录。
export const apiGetWorldCupMatchDetail = async (matchId) => {
  try {
    const response = await get(
      `${WORLD_CUP_API_PREFIX}/match/detail?matchId=${encodeURIComponent(matchId)}`,
    )
    return response
  } catch (error) {
    logWorldCupApiError('Failed to get world cup match detail:', error)
    throw error
  }
}
