import { fetchResults, makeFetch } from "ChillMainAssets/lib/api/apiMethods";
import { Center, Civility, Gender, SetCenter } from "ChillMainAssets/types";
import {
  AltName,
  Person,
  PersonIdentifier,
  PersonIdentifierWorker,
  PersonWrite,
} from "ChillPersonAssets/types";
import person from "ChillPersonAssets/vuejs/_components/OnTheFly/Person.vue";

/*
 * GET a person by id
 */
export const getPerson = async (id: number): Promise<Person> => {
  const url = `/api/1.0/person/person/${id}.json`;
  return fetch(url).then((response) => {
    if (response.ok) {
      return response.json();
    }
    throw Error("Error with request resource response");
  });
};

export const personToWritePerson = (person: Person): PersonWrite => {
  return {
    type: "person",
    firstName: person.firstName,
    lastName: person.lastName,
    altNames: person.altNames.map((altName) => ({
      key: altName.key,
      value: altName.label,
    })),
    addressId: null,
    birthdate:
      null === person.birthdate
        ? null
        : { datetime: person.birthdate.datetime8601 },
    deathdate:
      null === person.deathdate
        ? null
        : { datetime: person.deathdate.datetime8601 },
    phonenumber: person.phonenumber,
    mobilenumber: person.mobilenumber,
    center:
      null === person.centers
        ? null
        : person.centers
            .map((center): SetCenter => ({ id: center.id, type: "center" }))
            .find(() => true) || null,
    email: person.email,
    civility:
      null === person.civility
        ? null
        : { id: person.civility.id, type: "chill_main_civility" },
    gender:
      null === person.gender
        ? null
        : { id: person.gender.id, type: "chill_main_gender" },
    identifiers: person.identifiers.map((identifier: PersonIdentifier) => ({
      type: "person_identifier",
      definition_id: identifier.definition.id,
      value: identifier.value,
    })),
  };
};

export const getPersonAltNames = async (): Promise<AltName[]> =>
  fetch("/api/1.0/person/config/alt_names.json").then((response) => {
    if (response.ok) {
      return response.json();
    }
    throw Error("Error with request resource response");
  });

export const getCivilities = async (): Promise<Civility[]> =>
  fetchResults("/api/1.0/main/civility.json");

export const getGenders = async (): Promise<Gender[]> =>
  fetchResults("/api/1.0/main/gender.json");

export const getCentersForPersonCreation = async (): Promise<{
  showCenters: boolean;
  centers: Center[];
}> => makeFetch("GET", "/api/1.0/person/creation/authorized-centers", null);

export const getPersonIdentifiers = async (): Promise<
  PersonIdentifierWorker[]
> => fetchResults("/api/1.0/person/identifiers/workers");

export interface WritePersonViolationMap extends Record<
  string,
  Record<string, string>
> {
  firstName: {
    "{{ value }}": string;
  };
  lastName: {
    "{{ value }}": string;
  };
  gender: {
    "{{ value }}": string;
  };
  mobilenumber: {
    "{{ types }}": string; // ex: "mobile number"
    "{{ value }}": string; // ex: "+33 1 02 03 04 05"
  };
  phonenumber: {
    "{{ types }}": string; // ex: "mobile number"
    "{{ value }}": string; // ex: "+33 1 02 03 04 05"
  };
  email: {
    "{{ value }}": string;
  };
  center: {
    "{{ value }}": string;
  };
  civility: {
    "{{ value }}": string;
  };
  birthdate: {};
  identifiers: {
    "{{ value }}": string;
    definition_id: string;
  };
}
export const createPerson = async (person: PersonWrite): Promise<Person> => {
  return makeFetch<PersonWrite, Person, WritePersonViolationMap>(
    "POST",
    "/api/1.0/person/person.json",
    person,
  );
};

export const editPerson = async (
  person: PersonWrite,
  personId: number,
): Promise<Person> => {
  return makeFetch<PersonWrite, Person, WritePersonViolationMap>(
    "PATCH",
    `/api/1.0/person/person/${personId}.json`,
    person,
  );
};
