import request from '@/utils/request';
import type { ApiResult, PageResult } from '@/api';
import type { Member, MemberParam } from './model';

/**
 * 分页查询会员
 */
export async function pageMembers(params: MemberParam) {
  const res = await request.get<ApiResult<PageResult<Member>>>(
    '/shop/member/page',
    { params }
  );
  if (res.data.code === 0) {
    return res.data.data;
  }
  return Promise.reject(new Error(res.data.message));
}

/**
 * 查询会员列表
 */
export async function listMembers(params?: MemberParam) {
  const res = await request.get<ApiResult<Member[]>>('/shop/member', {
    params
  });
  if (res.data.code === 0 && res.data.data) {
    return res.data.data;
  }
  return Promise.reject(new Error(res.data.message));
}

/**
 * 添加会员
 */
export async function addMember(data: Member) {
  const res = await request.post<ApiResult<unknown>>('/shop/member', data);
  if (res.data.code === 0) {
    return res.data.message;
  }
  return Promise.reject(new Error(res.data.message));
}

/**
 * 修改会员
 */
export async function updateMember(data: Member) {
  const res = await request.put<ApiResult<unknown>>('/shop/member', data);
  if (res.data.code === 0) {
    return res.data.message;
  }
  return Promise.reject(new Error(res.data.message));
}

/**
 * 删除会员
 */
export async function removeMember(id?: number) {
  const res = await request.delete<ApiResult<unknown>>('/shop/member/' + id);
  if (res.data.code === 0) {
    return res.data.message;
  }
  return Promise.reject(new Error(res.data.message));
}

/**
 * 批量删除会员
 */
export async function removeMembers(data: (number | undefined)[]) {
  const res = await request.delete<ApiResult<unknown>>('/shop/member/batch', {
    data
  });
  if (res.data.code === 0) {
    return res.data.message;
  }
  return Promise.reject(new Error(res.data.message));
}
