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

/**
 * 上报浏览记录（异步静默，不抛错影响主流程）
 */
export async function reportBrowse(data: Partial<ShopGoodsBrowse>): Promise<void> {
  try {
    await request.post<ApiResult<unknown>>('/shop/shop-goods-browse', data);
  } catch {
    /* 静默失败：浏览记录上报不影响用户体验 */
  }
}

/**
 * 分页查询我的浏览记录
 */
export async function pageBrowseHistory(params: ShopGoodsBrowseParam) {
  const res = await request.get<ApiResult<PageResult<ShopGoodsBrowse>>>(
    '/shop/shop-goods-browse/page',
    params
  );
  if (res.code === 0) {
    return res.data;
  }
  return Promise.reject(new Error(res.message));
}

/**
 * 删除单条浏览记录
 */
export async function deleteBrowseRecord(id: number) {
  const res = await request.del<ApiResult<unknown>>(
    `/shop/shop-goods-browse/${id}`
  );
  if (res.code === 0) {
    return res.message;
  }
  return Promise.reject(new Error(res.message));
}

/**
 * 清空我的浏览记录
 */
export async function clearBrowseHistory() {
  const res = await request.del<ApiResult<unknown>>('/shop/shop-goods-browse');
  if (res.code === 0) {
    return res.message;
  }
  return Promise.reject(new Error(res.message));
}
