import request from '@/utils/request';
import type { ApiResult, PageResult } from '@/api/index';
import type { ViewHistory, ViewHistoryParam } from './model';
import { MODULES_API_URL } from '@/config/setting';

/**
 * 分页查询浏览历史
 */
export async function pageViewHistory(params: ViewHistoryParam) {
  const res = await request.get<ApiResult<PageResult<ViewHistory>>>(
    MODULES_API_URL + '/shop/view-history/page',
    {
      params
    }
  );
  if (res.data.code === 0) {
    return res.data.data;
  }
  return Promise.reject(new Error(res.data.message));
}

/**
 * 查询浏览历史列表
 */
export async function listViewHistory(params?: ViewHistoryParam) {
  const res = await request.get<ApiResult<ViewHistory[]>>(
    MODULES_API_URL + '/shop/view-history',
    {
      params
    }
  );
  if (res.data.code === 0 && res.data.data) {
    return res.data.data;
  }
  return Promise.reject(new Error(res.data.message));
}

/**
 * 添加浏览历史
 */
export async function addViewHistory(data: ViewHistory) {
  const res = await request.post<ApiResult<unknown>>(
    MODULES_API_URL + '/shop/view-history',
    data
  );
  if (res.data.code === 0) {
    return res.data.message;
  }
  return Promise.reject(new Error(res.data.message));
}

/**
 * 修改浏览历史
 */
export async function updateViewHistory(data: ViewHistory) {
  const res = await request.put<ApiResult<unknown>>(
    MODULES_API_URL + '/shop/view-history',
    data
  );
  if (res.data.code === 0) {
    return res.data.message;
  }
  return Promise.reject(new Error(res.data.message));
}

/**
 * 删除浏览历史
 */
export async function removeViewHistory(id?: number) {
  const res = await request.delete<ApiResult<unknown>>(
    MODULES_API_URL + '/shop/view-history/' + id
  );
  if (res.data.code === 0) {
    return res.data.message;
  }
  return Promise.reject(new Error(res.data.message));
}

/**
 * 批量删除浏览历史
 */
export async function removeBatchViewHistory(data: (number | undefined)[]) {
  const res = await request.delete<ApiResult<unknown>>(
    MODULES_API_URL + '/shop/view-history/batch',
    {
      data
    }
  );
  if (res.data.code === 0) {
    return res.data.message;
  }
  return Promise.reject(new Error(res.data.message));
}

/**
 * 根据id查询浏览历史
 */
export async function getViewHistory(id: number) {
  const res = await request.get<ApiResult<ViewHistory>>(
    MODULES_API_URL + '/shop/view-history/' + id
  );
  if (res.data.code === 0 && res.data.data) {
    return res.data.data;
  }
  return Promise.reject(new Error(res.data.message));
}
