"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`;

function iterateOverPageLayers(
  availableEventsList: any,
  availablePages: any,
  iterLevel: any
) {
  console.log("iterLevel", iterLevel);
  if (Array.isArray(iterLevel)) {
    iterLevel.map((page: any) => {
      const pageInfo = page?.pageInfo?.tr || [];
      if (pageInfo.length > 0) {
        pageInfo.map((pageInfoItem: any) => {
          const endpoint = pageInfoItem?.endpoint || "";
          if (
            availableEventsList.includes(endpoint) &&
            !availablePages.includes(page.name)
          ) {
            if (page.name) {
              availablePages.push(page.name);
            }
            return;
          }
        });
      }
    });
  } else {
    const pageInfo = iterLevel?.pageInfo?.tr || [];
    if (pageInfo.length > 0) {
      pageInfo.map((pageInfoItem: any) => {
        const endpoint = pageInfoItem?.endpoint || "";
        if (
          availableEventsList.includes(endpoint) &&
          !availablePages.includes(iterLevel.name)
        ) {
          availablePages.push(iterLevel.name);
          return;
        }
      });
    }
  }
}

async function checkPageAvaliablityByEndpoint(availableEvents: any) {
  let availablePages: string[] = [];
  const availableEventsList: string[] = availableEvents || [];
  let pageLayers = null;
  PagesInfosAndEndpoints.map((page) => {
    if (page.subCategories) {
      pageLayers = page?.subCategories;
      if (pageLayers) {
        iterateOverPageLayers(availableEventsList, availablePages, pageLayers);

        const nestedLayers = pageLayers.find(
          (layer) => layer.subCategories
        )?.subCategories;
        if (nestedLayers) {
          iterateOverPageLayers(
            availableEventsList,
            availablePages,
            nestedLayers
          );
        }
      }
    }
    iterateOverPageLayers(availableEventsList, availablePages, page);
  });
  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
    );
    const availableEvents = await nextCrypto.encrypt(
      JSON.stringify({ availableEvents: availableEventData })
    );
    const availablePages = await nextCrypto.encrypt(
      JSON.stringify({ availablePages: availableEventDataRes })
    );
    cookieStore.set({
      name: "availableEvents",
      value: availableEvents,
      ...cookieObject,
    });
    cookieStore.set({
      name: "availablePages",
      value: availablePages,
      ...cookieObject,
    });
  }
}

export { setAvailableEvents };
