"use server";
import { fetchDataWithToken } from "../api-fetcher";
import { cookies } from "next/headers";
import { baseUrl, cookieObject, tokenSecret } from "../basics";
import NextCrypto from "next-crypto";
import { PagesInfosAndEndpoints } from "@/apimaps/mappingApi";

const availableEventsURL = `${baseUrl}/access/endpoints/available`;

async function checkPageAvaliablityByEndpoint(availableEvents: any) {
  let availablePages: string[] = [];
  const availableEventsList: string[] = availableEvents || [];
  PagesInfosAndEndpoints.map((page) => {
    const pageInfo = page?.pageInfo?.tr || [];
    if (pageInfo.length > 0) {
      pageInfo.map((pageInfoItem) => {
        const endpoint = pageInfoItem?.endpoint || "";
        if (
          availableEventsList.includes(endpoint) &&
          !availablePages.includes(page.name)
        ) {
          availablePages.push(page.name);
          return;
        }
      });
    }
  });
  return availablePages;
}

async function setAvailableEvents() {
  const cookieStore = await cookies();
  const nextCrypto = new NextCrypto(tokenSecret);

  const availableResponse: any = await fetchDataWithToken(
    availableEventsURL,
    {},
    "POST",
    false
  );

  if (availableResponse.status === 200) {
    const availableEventData = Array.from(availableResponse?.result) || [];
    const availableEventDataRes = await checkPageAvaliablityByEndpoint(
      availableEventData
    );
    console.log("availableEventDataRes", availableEventDataRes);
    const availableEvents = await nextCrypto.encrypt(
      JSON.stringify({ availableEvents: availableEventData })
    );
    cookieStore.set({
      name: "availableEvents",
      value: availableEvents,
      ...cookieObject,
    });
  }
}

export { setAvailableEvents };
