import request from '@/utils/request'
import type { ApiResult, PageResult } from '@/api'
import type {
  ShopActivity,
  ShopActivityParam,
  ActivitySignUpParams,
  ActivityStats,
} from './model'
import { normalizeActivity } from './model'

export type { ShopActivity, ActivityStatus, ActivityType } from './model'

/**
 * 分页查询活动
 */
export async function pageShopActivity(params: ShopActivityParam) {
  const res = await request.get<ApiResult<PageResult<ShopActivity>>>(
    '/shop/shop-activity/page',
    params
  )
  if (res.code === 0 && res.data) {
    return {
      ...res.data,
      list: (res.data.list || []).map(normalizeActivity),
    }
  }
  return Promise.reject(new Error(res.message))
}

/**
 * 查询活动列表
 */
export async function listShopActivity(params?: ShopActivityParam) {
  const res = await request.get<ApiResult<ShopActivity[]>>(
    '/shop/shop-activity',
    params
  )
  if (res.code === 0 && res.data) {
    return res.data.map(normalizeActivity)
  }
  return Promise.reject(new Error(res.message))
}

/**
 * 根据ID查询活动
 */
export async function getShopActivity(id: number) {
  const res = await request.get<ApiResult<ShopActivity>>(
    '/shop/shop-activity/' + id
  )
  if (res.code === 0 && res.data) {
    return normalizeActivity(res.data)
  }
  return Promise.reject(new Error(res.message))
}

/**
 * 报名活动
 */
export async function signUpActivity(params: ActivitySignUpParams) {
  const res = await request.post<ApiResult<unknown>>(
    '/shop/shop-activity/sign-up',
    params
  )
  if (res.code === 0) {
    return res.message
  }
  return Promise.reject(new Error(res.message))
}

/**
 * 取消报名
 */
export async function cancelSignUpActivity(activityId: number) {
  const res = await request.post<ApiResult<unknown>>(
    '/shop/shop-activity/cancel-sign-up',
    { activityId }
  )
  if (res.code === 0) {
    return res.message
  }
  return Promise.reject(new Error(res.message))
}

/**
 * 获取活动报名状态
 */
export async function getSignUpStatus(activityId: number) {
  const res = await request.get<ApiResult<{ signedUp: boolean }>>(
    '/shop/shop-activity/sign-up-status',
    { activityId }
  )
  if (res.code === 0 && res.data) {
    return res.data
  }
  return Promise.reject(new Error(res.message))
}

/**
 * 获取活动统计
 */
export async function getActivityStats() {
  const res = await request.get<ApiResult<ActivityStats>>(
    '/shop/shop-activity/stats'
  )
  if (res.code === 0 && res.data) {
    return res.data
  }
  return Promise.reject(new Error(res.message))
}
