import {
  Address,
  GeographicalUnitLayer,
  SimpleGeographicalUnit,
} from "../../types";
import { fetchResults, makeFetch } from "./apiMethods";

export const getAddressById = async (address_id: number): Promise<Address> => {
  const url = `/api/1.0/main/address/${address_id}.json`;

  const response = await fetch(url);

  if (response.ok) {
    return response.json();
  }

  throw Error("Error with request resource response");
};

export const getGeographicalUnitsByAddress = async (
  address: Address,
): Promise<SimpleGeographicalUnit[]> => {
  return fetchResults<SimpleGeographicalUnit>(
    `/api/1.0/main/geographical-unit/by-address/${address.address_id}.json`,
  );
};

export const getAllGeographicalUnitLayers = async (): Promise<
  GeographicalUnitLayer[]
> => {
  return fetchResults<GeographicalUnitLayer>(
    `/api/1.0/main/geographical-unit-layer.json`,
  );
};

export const syncAddressWithReference = async (
  address: Address,
): Promise<Address> => {
  return makeFetch<null, Address>(
    "POST",
    `/api/1.0/main/address/reference-match/${address.address_id}/sync-with-reference`,
  );
};

export const markAddressReviewed = async (
  address: Address,
): Promise<Address> => {
  return makeFetch<null, Address>(
    "POST",
    `/api/1.0/main/address/reference-match/${address.address_id}/set/reviewed`,
  );
};

export const markAddressToReview = async (
  address: Address,
): Promise<Address> => {
  return makeFetch<null, Address>(
    "POST",
    `/api/1.0/main/address/reference-match/${address.address_id}/set/to_review`,
  );
};
