/*
 * GET a thirdparty by id
 */
import {
  isThirdpartyChild,
  isThirdpartyCompany,
  isThirdpartyContact,
  Thirdparty,
  ThirdPartyWrite,
} from "../../types";
import { makeFetch } from "ChillMainAssets/lib/api/apiMethods";

export const getThirdparty = async (id: number): Promise<Thirdparty> => {
  const url = `/api/1.0/thirdparty/thirdparty/${id}.json`;
  return fetch(url).then((response) => {
    if (response.ok) {
      return response.json();
    }
    throw Error("Error with request resource response");
  });
};

export const thirdpartyToWriteThirdParty = (t: Thirdparty): ThirdPartyWrite => {
  // Determine kind-specific fields using available type guards
  const isCompany = isThirdpartyCompany(t);
  const isContact = isThirdpartyContact(t);
  const isChild = isThirdpartyChild(t);

  return {
    type: "thirdparty",
    kind: t.kind,
    civility:
      (isContact || isChild) && t.civility
        ? { type: "chill_main_civility", id: t.civility.id }
        : null,
    profession: isContact || isChild ? (t.profession ?? "") : "",
    firstname: isCompany ? "" : (t.firstname ?? ""),
    name: isCompany ? (t.nameCompany ?? "") : (t.name ?? ""),
    email: t.email ?? "",
    telephone: t.telephone ?? "",
    telephone2: t.telephone2 ?? "",
    address: null,
    comment: isChild ? (t.comment ?? "") : "",
    parent:
      isChild && t.parent ? { type: "thirdparty", id: t.parent.id } : null,
  };
};

export interface WriteThirdPartyViolationMap extends Record<
  string,
  Record<string, string>
> {
  email: {
    "{{ value }}": string;
  };
  name: {
    "{{ value }}": string;
  };
  telephone: {
    "{{ value }}": string;
  };
  telephone2: {
    "{{ value }}": string;
  };
}

/*
 * POST a new thirdparty
 */
export const createThirdParty = async (body: ThirdPartyWrite) => {
  const url = `/api/1.0/thirdparty/thirdparty.json`;

  return makeFetch<ThirdPartyWrite, Thirdparty>("POST", url, body);
};

/*
 * PATCH an existing thirdparty
 */
export const patchThirdparty = async (
  id: number,
  body: ThirdPartyWrite,
): Promise<Thirdparty> => {
  const url = `/api/1.0/thirdparty/thirdparty/${id}.json`;
  return makeFetch("PATCH", url, body);
};
