import { Alert } from "react-native";
import { errorRecord } from "../../common/libEventLog/libCrashlytics/libCrashlyticsEvent";
import { SELF_SURVEY_SERVICES_ACTIVITYID } from "../../Api/ApiUrls";
import {
  UEEndTimer,
  UELogEvent, UELogMessage, UEStartTimer
} from "../../common/libEventLog/UserExperior/LibUserExperior"

// instructions
export const getActivityid = async ({ body }) => {

  UELogEvent("Get Activity Id API call started", {
    "payload": JSON.stringify(body),
    "url": `${SELF_SURVEY_SERVICES_ACTIVITYID}customer/preInspection`
  })

  const url = `${SELF_SURVEY_SERVICES_ACTIVITYID}customer/preInspection`;

  UEStartTimer(url);
  try {
    console.log("URL >>  ", url);
    const res = await fetch(url, {
      headers: {
        "Content-Type": "application/json",
      },
      method: "POST",
      body: JSON.stringify(body),
    });

    let data = await res.json();

    if (res.status !== 200) {

      UELogMessage(`Status ${res.status}`, {
        "Error": data?.error
      })

      if (res.status === 412) {
        UELogEvent(`User got suggested for manual inspection`, {
          "response": JSON.stringify(data)
        })
        return {
          data,
          flag: "Manual Inspection"
        }
      }

      throw new Error(data?.error);
    }

    UELogEvent("Get Activity Id API call ended in Try", {
      "response": JSON.stringify(data),
    })

    UEEndTimer(url);
    return data;
  } catch (err) {
    UELogEvent("Get Activity Id API call ended in Catch", {
      "error": JSON.stringify(err),
    })

    errorRecord(err);
    console.log(err);
    throw new Error(err?.message);
  }
};
