import { fetchWrapper } from "@/shared/fetchWrapper";
import moment from "moment/moment";

export async function updatePerson(data, initialData) {
  const dataPerson = {
    full_name: data.full_name,
    birth_date: moment(data.birth_date).format("YYYY-MM-DD"),
    insurance_number: data.insurance_number,
    gender: data.gender,
    benefit_code: data.benefit_code,
  };
  const notEmptyData = {};
  Object.keys(dataPerson).forEach((key) => {
    if (dataPerson[key] && initialData[key] !== dataPerson[key]) {
      notEmptyData[key] = dataPerson[key];
    }
  });
  return Object.keys(notEmptyData).length
    ? fetchWrapper
        .post(`general/person/${data.id}/update/`, notEmptyData)
        .then((res) => res)
    : Promise.resolve();
}

export async function requestAddress(data, initialData) {
  const registrationInit = initialData.address.find(
    (add) => add.registration_flg
  );
  const temporaryInit = initialData.address.find(
    (add) => add.temporary_registration_flg
  );
  let resultRequestRegistration = Promise.resolve();
  let resultRequestTemporary = Promise.resolve();
  if (!registrationInit && data.registration_address) {
    resultRequestRegistration = fetchWrapper.post(`general/address/create/`, {
      person: data.id,
      full_address: data.registration_address,
      registration_flg: true,
    });
  }
  if (
    registrationInit &&
    registrationInit.join_address !== data.registration_address
  ) {
    resultRequestRegistration = fetchWrapper.post(
      `general/address/${registrationInit.id}/update/`,
      {
        full_address: data.registration_address,
      }
    );
  }
  if (!temporaryInit && data.temporary_address) {
    resultRequestTemporary = fetchWrapper.post(`general/address/create/`, {
      person: data.id,
      full_address: data.temporary_address,
      temporary_registration_flg: true,
    });
  }
  if (temporaryInit && temporaryInit.join_address !== data.temporary_address) {
    resultRequestTemporary = fetchWrapper.post(
      `general/address/${registrationInit.id}/update/`,
      {
        full_address: data.temporary_address,
      }
    );
  }
  return Promise.all([resultRequestRegistration, resultRequestTemporary]);
}

export async function requestContacts(data, dataInit) {
  const phoneInit = dataInit.contacts.find((el) => el.kind === "PHONE");
  const emailInit = dataInit.contacts.find((el) => el.kind === "EMAIL");
  let resultRequestPhone = Promise.resolve();
  let resultRequestEmail = Promise.resolve();
  if (!phoneInit && data.phone) {
    resultRequestPhone = fetchWrapper.post(`general/contact/create/`, {
      person: data.id,
      username: data.phone,
      kind: "PHONE",
    });
  }
  if (phoneInit && phoneInit?.username !== data.phone) {
    resultRequestPhone = fetchWrapper.post(
      `general/contact/${phoneInit.id}/update/`,
      {
        person: data.id,
        username: data.phone,
        kind: "PHONE",
      }
    );
  }
  if (!emailInit && data.email) {
    resultRequestEmail = fetchWrapper.post(`general/contact/create/`, {
      person: data.id,
      username: data.email,
      kind: "EMAIL",
    });
  }
  if (emailInit && emailInit?.username !== data.email) {
    resultRequestEmail = fetchWrapper.post(
      `general/contact/${emailInit.id}/update/`,
      {
        person: data.id,
        username: data.email,
        kind: "EMAIL",
      }
    );
  }
  return Promise.all([resultRequestPhone, resultRequestEmail]);
}

export async function requestIdentityDoc(data, dataInit) {
  const receivedDoc = dataInit.identity_documents.find(
    (doc) => doc.kind === "PASSPORT"
  );
  const transformReceivedDoc = {
    ...receivedDoc,
    series_number:
      receivedDoc?.series && receivedDoc?.number
        ? `${receivedDoc.series} ${receivedDoc.number}`
        : "",
  };
  const dataIdentity = {
    ...data.identity_documents,
    issued_by_date: moment(data.identity_documents.issued_by_date).format(
      "YYYY-MM-DD"
    ),
  };
  const notEmptyIdentityDoc = {};
  Object.keys(dataIdentity).forEach((key) => {
    if (dataIdentity[key] && dataIdentity[key] !== transformReceivedDoc[key]) {
      notEmptyIdentityDoc[key] = dataIdentity[key];
    }
  });
  if (Object.keys(notEmptyIdentityDoc).length) {
    if (!receivedDoc) {
      return fetchWrapper.post(`general/identity_document/create/`, {
        ...notEmptyIdentityDoc,
        person: dataInit.id,
      });
    } else {
      return fetchWrapper.post(
        `general/identity_document/${receivedDoc.id}/update/`,
        {
          ...notEmptyIdentityDoc,
        }
      );
    }
  } else {
    return Promise.resolve();
  }
}

export async function requestPolicy(data, dataInit) {
  const policyInit =
    data.policy === "OMS"
      ? dataInit.insurance_policy.find((el) => el.title === "OMS")
      : dataInit.insurance_policy.find((el) => el.title === "DMS");
  const dataPolicy = data.policy === "OMS" ? data.OMSPolicy : data.DMSPolicy;
  const dataRequest = {
    organization: dataPolicy.organization,
    series: dataPolicy.number.split(" ")[0],
    number: dataPolicy.number.split(" ")[1],
  };
  const notEmptyPolicy = {};
  Object.keys(dataRequest).forEach((key) => {
    if (!policyInit && dataRequest[key]) {
      notEmptyPolicy[key] = dataRequest[key];
    }
    if (policyInit && policyInit[key] !== dataRequest[key]) {
      notEmptyPolicy[key] = dataRequest[key];
    }
  });
  if (Object.keys(notEmptyPolicy).length) {
    if (!policyInit) {
      return fetchWrapper.post(`general/insurance_policy/create/`, {
        ...notEmptyPolicy,
        title: data.policy,
        person: data.id,
      });
    } else {
      return fetchWrapper.post(
        `general/insurance_policy/${policyInit.id}/update/`,
        {
          ...notEmptyPolicy,
          title: data.policy,
        }
      );
    }
  } else {
    return Promise.resolve();
  }
}
export async function requestMedicalCardData(data, init) {
  return Promise.allSettled([
    updatePerson(data, init),
    requestAddress(data, init),
    requestContacts(data, init),
    requestIdentityDoc(data, init),
    requestPolicy(data, init),
  ]);
}
