import { makeFetch } from "ChillMainAssets/lib/api/apiMethods";

/**
 * Endpoint chill_api_single_postal_code__index
 * method GET, get Cities Object
 * @params {object} a country object
 * @returns {Promise} a promise containing all Postal Code objects filtered with country
 */
const fetchCities = (country) => {
  // warning: do not use fetchResults (in apiMethods): we need only a **part** of the results in the db
  const params = new URLSearchParams({ item_per_page: 100 });

  if (country !== null) {
    params.append("country", country.id);
  }

  return makeFetch(
    "GET",
    `/api/1.0/main/postal-code.json?${params.toString()}`,
  ).then((r) => Promise.resolve(r.results));
};

/**
 * Endpoint chill_main_postalcodeapi_search
 * method GET, get Cities Object
 * @params {string} search a search string
 * @params {object} country a country object
 * @params {AbortController} an abort controller
 * @returns {Promise} a promise containing all Postal Code objects filtered with country and a search string
 */
const searchCities = (search, country, controller) => {
  const url = "/api/1.0/main/postal-code/search.json?";
  const params = new URLSearchParams({ q: search });

  if (country !== null) {
    Object.assign("country", country.id);
  }

  return makeFetch("GET", url + params, null, {
    signal: controller.signal,
  }).then((result) => Promise.resolve(result.results));
};

export { fetchCities, searchCities };
