"use client";
import { retrieveUserSelection } from "@/apicalls/cookies/token";
import { retrieveHeadersAndValidationByEndpoint } from "@/apicalls/validations/validations";
import { AvailableLanguages } from "@/apimaps/mappingApi";
import { checkEndpointAvailability } from "@/apimaps/mappingApiFunctions";
import { retrievePageInfoByComponentName } from "./retrievePageInfoByComponentName";

async function initializePageRequirements(
  endpoint: string,
  pageInfoFromApi: Array<{ endpoint: string; [key: string]: any }>,
  setFunction: Function,
  setterFunction: Function
): Promise<void> {
  try {
    const validation = await retrieveHeadersAndValidationByEndpoint({
      endpoint: endpoint,
    });
    const pageInfo = pageInfoFromApi.find(
      (page: { endpoint: string }) => page.endpoint === endpoint
    );

    if (pageInfo && validation.status === 200) {
      setFunction({
        ...pageInfo,
        validation: validation.validated,
        headers: validation.headers,
        setterFunction: setterFunction,
      });
    }
  } catch (error) {
    console.error(`Error initializing endpoint ${endpoint}:`, error);
  }
}

interface Mapper {
  setFunction: Function;
  setterFunction: Function;
}

async function initializePageContent(
  pageName: string,
  eventsAvailable: any,
  MappingBuild: Record<string, Mapper>
): Promise<void> {
  try {
    const user = await retrieveUserSelection();
    if (!AvailableLanguages.includes((user?.lang as string) || "")) {
      new Error("Language not available");
    }

    const pageContent = retrievePageInfoByComponentName(pageName, user?.lang);
    if (!Array.isArray(pageContent)) return;
    await Promise.all(
      Object.entries(MappingBuild).map(async ([endpoint, mapper]) => {
        const { setFunction, setterFunction } = mapper as Mapper;
        if (checkEndpointAvailability(endpoint, eventsAvailable)) {
          await initializePageRequirements(
            endpoint,
            pageContent,
            setFunction,
            setterFunction
          );
        }
      })
    );
  } catch (error) {
    console.error("Error initializing page content:", error);
  }
}

export { initializePageRequirements, initializePageContent };
