import request from '@/utils/request'
import type { ApiResult, PageResult } from '@/api'
import type {
  ShopEvaluation,
  ShopEvaluationParam,
  CreateEvaluationParams,
  LikeEvaluationParams,
  EvaluationStats,
} from './model'

/**
 * 分页查询评价
 */
export async function pageShopEvaluation(params: ShopEvaluationParam) {
  const res = await request.get<ApiResult<PageResult<ShopEvaluation>>>(
    '/shop/shop-evaluation/page',
    params
  )
  if (res.code === 0) {
    return res.data
  }
  return Promise.reject(new Error(res.message))
}

/**
 * 查询评价列表
 */
export async function listShopEvaluation(params?: ShopEvaluationParam) {
  const res = await request.get<ApiResult<ShopEvaluation[]>>(
    '/shop/shop-evaluation',
    params
  )
  if (res.code === 0 && res.data) {
    return res.data
  }
  return Promise.reject(new Error(res.message))
}

/**
 * 根据ID查询评价
 */
export async function getShopEvaluation(id: number) {
  const res = await request.get<ApiResult<ShopEvaluation>>(
    '/shop/shop-evaluation/' + id
  )
  if (res.code === 0 && res.data) {
    return res.data
  }
  return Promise.reject(new Error(res.message))
}

/**
 * 创建评价
 */
export async function createShopEvaluation(data: CreateEvaluationParams) {
  const res = await request.post<ApiResult<unknown>>(
    '/shop/shop-evaluation',
    data
  )
  if (res.code === 0) {
    return res.message
  }
  return Promise.reject(new Error(res.message))
}

/**
 * 删除评价
 */
export async function removeShopEvaluation(id?: number) {
  const res = await request.del<ApiResult<unknown>>(
    '/shop/shop-evaluation/' + id
  )
  if (res.code === 0) {
    return res.message
  }
  return Promise.reject(new Error(res.message))
}

/**
 * 点赞/取消点赞评价
 */
export async function likeShopEvaluation(params: LikeEvaluationParams) {
  const res = await request.post<ApiResult<unknown>>(
    '/shop/shop-evaluation/like',
    params
  )
  if (res.code === 0) {
    return res.message
  }
  return Promise.reject(new Error(res.message))
}

/**
 * 获取商品评价统计
 */
export async function getEvaluationStats(goodsId: number) {
  const res = await request.get<ApiResult<EvaluationStats>>(
    '/shop/shop-evaluation/stats',
    { goodsId }
  )
  if (res.code === 0 && res.data) {
    return res.data
  }
  return Promise.reject(new Error(res.message))
}

/**
 * 获取订单的评价信息（用于判断是否已评价）
 */
export async function getOrderEvaluationStatus(orderId: number) {
  const res = await request.get<ApiResult<{ evaluated: boolean; evaluationId?: number }>>(
    '/shop/shop-evaluation/order-status',
    { orderId }
  )
  if (res.code === 0 && res.data) {
    return res.data
  }
  return Promise.reject(new Error(res.message))
}
