import axios from "axios";
import config from "../config.ts";
import { EspoStatusUpdateQueue } from "../state.ts";

async function makeRequestToEspo(
  calendarId: (typeof EspoStatusUpdateQueue)[number]["calendarId"],
  status: (typeof EspoStatusUpdateQueue)[number]["status"]
): Promise<string> {
  try {
    const response = await axios.patch(
      `https://cam5.pixika.ai/api/v1/CSubmission/${calendarId}`,
      { aiFeatureStage: status },
      { headers: { "x-api-key": config.espo.key } }
    );
    return calendarId;
  } catch (error) {
    console.error(`Error updating calendar status in espo: ${error}`);
    throw error;
    return "";
  }
}

export function enqueUpdateCalendarStatusEspo(
  calendarId: (typeof EspoStatusUpdateQueue)[number]["calendarId"],
  status: (typeof EspoStatusUpdateQueue)[number]["status"]
) {
  // add the item to the queue
  EspoStatusUpdateQueue.push({ calendarId, status });
}

async function sendItems() {
  const results = await Promise.allSettled(
    EspoStatusUpdateQueue.map((item) =>
      makeRequestToEspo(item.calendarId, item.status)
    )
  );

  for (const result of results) {
    if (result.status === "fulfilled") {
      console.log("##############################################");
      console.log("Calendar status updated in espo", result.value);
      console.log("##############################################");

      console.log(
        "status update queue length before removal",
        EspoStatusUpdateQueue.length
      );
      // remove the item from the queue
      EspoStatusUpdateQueue.splice(
        EspoStatusUpdateQueue.findIndex(
          (item) => item.calendarId === result.value
        ),
        1
      );
      console.log(
        "status update queue length after removal",
        EspoStatusUpdateQueue.length
      );
    }
  }
}

async function espoStatusUpdateLoop() {
  while (true) {
    console.log(
      `EspoStatusUpdateQueue length: ${EspoStatusUpdateQueue.length}`
    );
    await new Promise((resolve) =>
      setTimeout(resolve, config.espoStatusUpdateLoopSleep)
    );
    await sendItems();
  }
}

export async function startEspoStatusService() {
  await espoStatusUpdateLoop();
}
