import request from '@/utils/request';
import type { ApiResult, PageResult } from '@/api';
import type {
  ShopRechargeCode,
  ShopRechargeCodeParam,
  BatchGenerateParams,
  BatchGenerateResult
} from './model';

/**
 * 分页查询兑换码
 */
export async function pageRechargeCode(params: ShopRechargeCodeParam) {
  const res = await request.get<ApiResult<PageResult<ShopRechargeCode>>>(
    '/shop/recharge-code/page',
    { params }
  );
  if (res.data.code === 0) {
    return res.data.data;
  }
  return Promise.reject(new Error(res.data.message));
}

/**
 * 生成兑换码
 * @param amount 充值金额
 * @param quantity 生成数量
 * @param expireDays 过期天数
 */
export async function generateRechargeCode(
  amount: number,
  quantity: number = 1,
  expireDays: number = 30
) {
  const res = await request.post<ApiResult<ShopRechargeCode[]>>(
    '/shop/recharge-code/generate',
    null,
    { params: { amount, quantity, expireDays } }
  );
  if (res.data.code === 0) {
    return res.data.data;
  }
  return Promise.reject(new Error(res.data.message));
}

/**
 * 批量生成兑换码
 */
export async function batchGenerateRechargeCode(params: BatchGenerateParams) {
  const res = await request.post<ApiResult<BatchGenerateResult>>(
    '/shop/recharge-code/batch-generate',
    params
  );
  if (res.data.code === 0) {
    return res.data.data;
  }
  return Promise.reject(new Error(res.data.message));
}

/**
 * 获取兑换码信息
 */
export async function getRechargeCodeInfo(code: string) {
  const res = await request.get<ApiResult<ShopRechargeCode>>(
    '/shop/recharge-code/info',
    { params: { code } }
  );
  if (res.data.code === 0 && res.data.data) {
    return res.data.data;
  }
  return Promise.reject(new Error(res.data.message));
}

/**
 * 根据批次号导出兑换码列表
 */
export async function exportRechargeCodeByBatch(batchNo: string) {
  const res = await request.get<ApiResult<ShopRechargeCode[]>>(
    `/shop/recharge-code/export/${batchNo}`
  );
  if (res.data.code === 0) {
    return res.data.data;
  }
  return Promise.reject(new Error(res.data.message));
}

/**
 * 删除兑换码
 */
export async function removeRechargeCode(id: number) {
  const res = await request.delete<ApiResult<unknown>>(
    `/shop/recharge-code/${id}`
  );
  if (res.data.code === 0) {
    return res.data.message;
  }
  return Promise.reject(new Error(res.data.message));
}
