import { Search, SearchOptions } from "ChillPersonAssets/types";

/*
 * Build query string with query and options
 */
const parametersToString = ({
  query,
  options,
}: {
  query: string;
  options: SearchOptions;
}) => {
  let types = "";
  options.type.forEach(function (type) {
    types += "&type[]=" + type;
  });
  return "q=" + query + types;
};

/*
 * Endpoint chill_person_search
 * method GET, get a list of persons
 *
 *  @query string - the query to search for
 *  @deprecated
 */
export function searchPersons(
  { query, options }: { query: string; options: SearchOptions },
  signal: AbortSignal,
): Promise<Search> {
  const queryStr = parametersToString({ query, options });
  const url = `/fr/search.json?name=person_regular&${queryStr}`;
  const fetchOpts = {
    method: "GET",
    headers: {
      "Content-Type": "application/json;charset=utf-8",
    },
    signal,
  };

  return fetch(url, fetchOpts).then((response) => {
    if (response.ok) {
      return response.json();
    }
    throw Error("Error with request resource response");
  });
}

/*
 * Endpoint v.2 chill_main_search_global
 * method GET, get a list of persons and thirdparty
 *
 * @param query string - the query to search for
 *
 */
export function searchEntities(
  { query, options }: { query: string; options: SearchOptions },
  signal: AbortSignal,
): Promise<Search> {
  const queryStr = parametersToString({ query, options });
  const url = `/api/1.0/search.json?${queryStr}`;
  return fetch(url, { signal }).then((response) => {
    if (response.ok) {
      return response.json();
    }
    throw Error("Error with request resource response");
  });
}
