import request from '@/utils/request';
import type { ApiResult, PageResult } from '@/api';
import type { App, AppParam } from './model/index';

/**
 * 分页查询应用
 */
export async function pageApp(params: AppParam) {
  const res = await request.get<ApiResult<PageResult<App>>>(
    '/open/market/page',
    {
      params
    }
  );
  if (res.data.code === 0) {
    return res.data.data;
  }
  return Promise.reject(new Error(res.data.message));
}

/**
 * 查询应用列表
 */
export async function listApp(params?: AppParam) {
  const res = await request.get<ApiResult<App[]>>('/open/market', {
    params
  });
  if (res.data.code === 0 && res.data.data) {
    return res.data.data;
  }
  return Promise.reject(new Error(res.data.message));
}

/**
 * 根据id查询应用
 */
export async function getApp(id: number) {
  const res = await request.get<ApiResult<App>>('/open/market/' + id);
  if (res.data.code === 0 && res.data.data) {
    return res.data.data;
  }
  return Promise.reject(new Error(res.data.message));
}

/**
 * 修改应用
 */
export async function updateApp(data: App) {
  const res = await request.put<ApiResult<unknown>>('/open/market', data);
  if (res.data.code === 0) {
    return res.data.message;
  }
  return Promise.reject(new Error(res.data.message));
}

// 排行榜
export async function ranking(params?: AppParam) {
  const res = await request.get<ApiResult<App[]>>('/open/market/ranking', {
    params
  });
  if (res.data.code === 0 && res.data.data) {
    return res.data.data;
  }
  return Promise.reject(new Error(res.data.message));
}

/**
 * 检查IP是否存在
 */
export async function checkExistence(
  field: string,
  value: string,
  id?: number
) {
  const res = await request.get<ApiResult<unknown>>('/open/market/existence', {
    params: { field, value, id }
  });
  if (res.data.code === 0) {
    return res.data.message;
  }
  return Promise.reject(new Error(res.data.message));
}

// 搜索历史
export async function searchHistory(params?: String) {
  const res = await request.get<ApiResult<String[]>>(
    '/open/market/search-history',
    {
      params
    }
  );
  if (res.data.code === 0 && res.data.data) {
    return res.data.data;
  }
  return Promise.reject(new Error(res.data.message));
}
