import request from '@/utils/request'
import type { ApiResult, PageResult } from '@/api'
import type {
  ShopEvent,
  ShopEventParam,
  EventRegisterParams,
  EventRegistration,
  RegistrationStatus,
} from './model'

export type { ShopEvent, EventRegistration, RegistrationStatus, EventStatus, EventFormField } from './model'
export { getEventStatusLabel, getPayStatusLabel } from './model'

/**
 * 分页查询赛事
 */
export async function pageShopEvent(params: ShopEventParam) {
  const res = await request.get<ApiResult<PageResult<ShopEvent>>>(
    '/shop/shop-event/page',
    params
  )
  if (res.code === 0 && res.data) return res.data
  return Promise.reject(new Error(res.message))
}

/**
 * 赛事详情
 */
export async function getShopEvent(id: number) {
  const res = await request.get<ApiResult<ShopEvent>>(`/shop/shop-event/${id}`)
  if (res.code === 0 && res.data) return res.data
  return Promise.reject(new Error(res.message))
}

/**
 * 提交报名（免费返回 {success,free}，收费返回微信支付参数）
 */
export async function registerEvent(data: EventRegisterParams) {
  const res = await request.post<ApiResult<Record<string, any>>>(
    '/shop/shop-event/register',
    data
  )
  if (res.code === 0 && res.data) return res.data
  return Promise.reject(new Error(res.message))
}

/**
 * 重新发起支付
 */
export async function payEventRegistration(registrationId: number) {
  const res = await request.post<ApiResult<Record<string, string>>>(
    '/shop/shop-event/pay',
    { registrationId }
  )
  if (res.code === 0 && res.data) return res.data
  return Promise.reject(new Error(res.message))
}

/**
 * 查询报名状态
 */
export async function getRegistrationStatus(eventId: number) {
  const res = await request.get<ApiResult<RegistrationStatus>>(
    '/shop/shop-event/registration-status',
    { eventId }
  )
  if (res.code === 0 && res.data) return res.data
  return Promise.reject(new Error(res.message))
}

/**
 * 我的报名记录
 */
export async function getMyRegistrations() {
  const res = await request.get<ApiResult<EventRegistration[]>>(
    '/shop/shop-event/my-registrations'
  )
  if (res.code === 0 && res.data) return res.data
  return Promise.reject(new Error(res.message))
}
