import request from '@/utils/request';
import type { ApiResult, PageResult } from '@/api';
import type {
  ShopMemberBenefitPackage,
  ShopMemberBenefitPackageParam,
  ShopMemberBenefitExchange,
  ShopMemberBenefitExchangeParam,
  ShipRequest
} from './model';

/**
 * 分页查询权益包列表
 */
export async function getBenefitPackagePage(
  params: ShopMemberBenefitPackageParam
) {
  const res = await request.get<ApiResult<PageResult<ShopMemberBenefitPackage>>>(
    '/shop/shop-member-benefit-package/page',
    { params }
  );
  if (res.data.code === 0) {
    return res.data.data;
  }
  return Promise.reject(new Error(res.data.message));
}

/**
 * 新增权益包
 */
export async function addBenefitPackage(data: ShopMemberBenefitPackage) {
  const res = await request.post<ApiResult<unknown>>(
    '/shop/shop-member-benefit-package',
    data
  );
  if (res.data.code === 0) {
    return res.data.message;
  }
  return Promise.reject(new Error(res.data.message));
}

/**
 * 修改权益包
 */
export async function updateBenefitPackage(data: ShopMemberBenefitPackage) {
  const res = await request.put<ApiResult<unknown>>(
    '/shop/shop-member-benefit-package',
    data
  );
  if (res.data.code === 0) {
    return res.data.message;
  }
  return Promise.reject(new Error(res.data.message));
}

/**
 * 删除权益包
 */
export async function deleteBenefitPackage(id: number) {
  const res = await request.delete<ApiResult<unknown>>(
    `/shop/shop-member-benefit-package/${id}`
  );
  if (res.data.code === 0) {
    return res.data.message;
  }
  return Promise.reject(new Error(res.data.message));
}

/**
 * 分页查询兑换记录
 */
export async function getBenefitExchangePage(
  params: ShopMemberBenefitExchangeParam
) {
  const res = await request.get<ApiResult<PageResult<ShopMemberBenefitExchange>>>(
    '/shop/shop-member-benefit-exchange/page',
    { params }
  );
  if (res.data.code === 0) {
    return res.data.data;
  }
  return Promise.reject(new Error(res.data.message));
}

/**
 * 获取兑换记录列表（向后兼容）
 */
export function getBenefitExchangeList(params: ShopMemberBenefitExchangeParam) {
  return request.get('/shop/shop-member-benefit-exchange/page', { params });
}

/**
 * 发货
 */
export async function shipBenefitExchange(id: number, data: ShipRequest) {
  const res = await request.post<ApiResult<unknown>>(
    `/shop/shop-member-benefit-exchange/ship/${id}`,
    data
  );
  if (res.data.code === 0) {
    return res.data.message;
  }
  return Promise.reject(new Error(res.data.message));
}

/**
 * 标记完成
 */
export async function completeBenefitExchange(id: number) {
  const res = await request.post<ApiResult<unknown>>(
    `/shop/shop-member-benefit-exchange/complete/${id}`
  );
  if (res.data.code === 0) {
    return res.data.message;
  }
  return Promise.reject(new Error(res.data.message));
}
