import type { SearchHistoryRecord, UserLoginRequest, CurrentUser } from "@/types/user.types";
import type { Page } from "@/types/pagination.types"
import type { Response } from "@/types/response.types";
import type { AxiosResponse } from "axios";
import httpClient from "./httpClient";

const urlPrefix = "/gw/user";

function _url(path: string): string {
  return `${urlPrefix}${path}`;
}

function login(param: UserLoginRequest): Promise<AxiosResponse<Response<CurrentUser>>> {
  return httpClient.post<Response<CurrentUser>>(_url("/login"), param);
}

async function checkLogin(): Promise<boolean> {
  const resp = await httpClient.get("/gw/user/user/checkLogin");
  if (resp) {
    return true;
  }
  return false;
}

/**
 * 获取指定页码和数量的搜索历史记录
 * @param currentUser user对象的json字符串
 * @param page 页码
 * @param size 每页数量
 * @returns Promise
 */
export function fetchHistory(currentUser: string, page: number, size: number, dateNum: number) {
  const url = _url("/searchHistory/getMySearchHistory");
  currentUser =  encodeURIComponent(currentUser);
  const headers = { currentUser };
  const params = { page, size, dateNum };
  return httpClient.get<Response<Page<SearchHistoryRecord>>>(url, { params, headers });
}

export function delHistory(currentUser: string, id: number) {
  const url = _url("/searchHistory/delById/" + id);
  const headers = { currentUser };
  return httpClient.delete<Response<Object>>(url, { headers });
}

export function delAllHistory(currentUser: string) {
  const url = _url("/searchHistory/delAllByUserId");
  const headers = { currentUser };
  return httpClient.delete<Response<Object>>(url, { headers });
}

export default {
  login,
  checkLogin,
  fetchHistory,
  delHistory,
  delAllHistory,
}
