import request from '@/utils/request';
import type { ApiResult, PageResult } from '@/api';
import type { UserPointsLog, UserPointsLogParam, UserPointsStats } from './model';
import {SERVER_API_URL} from "@/utils/server";

/**
 * 分页查询用户积分记录
 */
export async function pageUserPointsLog(params: UserPointsLogParam) {
  const res = await request.get<ApiResult<PageResult<UserPointsLog>>>(
    SERVER_API_URL + '/sys/user-points-log/page',
    params
  );
  if (res.code === 0) {
    return res.data;
  }
  return Promise.reject(new Error(res.message));
}

/**
 * 查询用户积分记录列表
 */
export async function listUserPointsLog(params?: UserPointsLogParam) {
  const res = await request.get<ApiResult<UserPointsLog[]>>(
    SERVER_API_URL + '/sys/user-points-log',
    params
  );
  if (res.code === 0 && res.data) {
    return res.data;
  }
  return Promise.reject(new Error(res.message));
}

/**
 * 获取用户积分统计
 */
export async function getUserPointsStats(userId: number) {
  const res = await request.get<ApiResult<UserPointsStats>>(
    SERVER_API_URL + '/sys/user-points-log/stats',
    { userId }
  );
  if (res.code === 0 && res.data) {
    return res.data;
  }
  return Promise.reject(new Error(res.message));
}

/**
 * 根据id查询积分记录
 */
export async function getUserPointsLog(id: number) {
  const res = await request.get<ApiResult<UserPointsLog>>(
    SERVER_API_URL + '/sys/user-points-log/' + id
  );
  if (res.code === 0 && res.data) {
    return res.data;
  }
  return Promise.reject(new Error(res.message));
}

/**
 * 使用积分
 */
export async function usePoints(userId: number, points: number, reason: string, orderId?: number) {
  const res = await request.post<ApiResult<unknown>>(
    SERVER_API_URL + '/sys/user-points-log/use',
    { userId, points, reason, orderId }
  );
  if (res.code === 0) {
    return res.message;
  }
  return Promise.reject(new Error(res.message));
}
