import { errorRecord } from "../../common/libEventLog/libCrashlytics/libCrashlyticsEvent";
import { SUBMITPI_URL } from "../../Api/ApiUrls";

import {
  UELogEvent,
  UELogMessage,
  UEStartTimer,
  UEEndTimer,
} from "../../common/libEventLog/UserExperior/LibUserExperior";

// instructions
export const submitPI = async ({ body }) => {
  UELogEvent("SUBMITPI_URL call started", {
    payload: JSON.stringify(body),
    url: `${SUBMITPI_URL}`,
  });

  UEStartTimer(SUBMITPI_URL);
  try {
    const res = await fetch(`${SUBMITPI_URL}`, {
      method: "POST",
      headers: {
        "Content-Type": "application/json",
      },
      body: JSON.stringify(body),
    });
    let data = await res.json();

    if (res.status !== 200) {
      UELogMessage(`Status ${res.status}`, {
        Error: JSON.stringify(data?.error),
      });
      throw new Error(data?.error);
    }

    UELogEvent("SubmitPI call ended in Try", {
      response: JSON.stringify(data),
      "status":JSON.stringify(res.status)
    });

    UEEndTimer(SUBMITPI_URL);
    return data;
  } catch (err) {
    UELogEvent("SubmitPI call ended in Catch", {
      error: JSON.stringify(err),
    });
    errorRecord(err);
    console.log(err);
  }
};
