"use server";
import { fetchDataWithToken } from "@/apicalls/api-fetcher";
import { baseUrlAuth, tokenSecret } from "@/apicalls/basics";
import { cookies } from "next/headers";

import NextCrypto from "next-crypto";

const checkToken = `${baseUrlAuth}/authentication/token/check`;
const pageValid = `${baseUrlAuth}/authentication/page/valid`;
const siteUrls = `${baseUrlAuth}/authentication/sites/list`;

const nextCrypto = new NextCrypto(tokenSecret);

async function checkAccessTokenIsValid() {
  const response = await fetchDataWithToken(checkToken, {}, "GET", false);
  return response?.status === 200 || response?.status === 202 ? true : false;
}

async function retrievePageList() {
  const response: any = await fetchDataWithToken(siteUrls, {}, "GET", false);
  return response?.status === 200 || response?.status === 202
    ? response.data?.sites
    : null;
}

async function retrieveApplicationbyUrl(pageUrl: string) {
  const response: any = await fetchDataWithToken(
    pageValid,
    {
      page_url: pageUrl,
    },
    "POST",
    false
  );
  return response?.status === 200 || response?.status === 202
    ? response.data?.application
    : null;
}

async function retrieveAccessToken() {
  const cookieStore = await cookies();
  const encrpytAccessToken = cookieStore.get("accessToken")?.value || "";
  return encrpytAccessToken
    ? await nextCrypto.decrypt(encrpytAccessToken)
    : null;
}

async function retrieveUserType() {
  const cookieStore = await cookies();
  const encrpytaccessObject = cookieStore.get("accessObject")?.value || "{}";
  const decrpytUserType = JSON.parse(
    (await nextCrypto.decrypt(encrpytaccessObject)) || "{}"
  );
  return decrpytUserType ? decrpytUserType : null;
}

async function retrieveAccessObjects() {
  const cookieStore = await cookies();
  const encrpytAccessObject = cookieStore.get("accessObject")?.value || "";
  const decrpytAccessObject = await nextCrypto.decrypt(encrpytAccessObject);
  return decrpytAccessObject ? JSON.parse(decrpytAccessObject) : null;
}

async function retrieveUserSelection() {
  const cookieStore = await cookies();
  const encrpytUserSelection = cookieStore.get("userSelection")?.value || "";

  let objectUserSelection = {};
  let decrpytUserSelection: any = await nextCrypto.decrypt(
    encrpytUserSelection
  );
  decrpytUserSelection = decrpytUserSelection
    ? JSON.parse(decrpytUserSelection)
    : null;
  const userSelection = decrpytUserSelection?.selected;
  const accessObjects = (await retrieveAccessObjects()) || {};

  if (decrpytUserSelection?.user_type === "employee") {
    const companyList = accessObjects?.selectionList;
    const selectedCompany = companyList.find(
      (company: any) => company.uu_id === userSelection
    );
    if (selectedCompany) {
      objectUserSelection = { userType: "employee", selected: selectedCompany };
    }
  } else if (decrpytUserSelection?.user_type === "occupant") {
    const buildingsList = accessObjects?.selectionList;

    // Iterate through all buildings
    if (buildingsList) {
      // Loop through each building
      for (const buildKey in buildingsList) {
        const building = buildingsList[buildKey];

        // Check if the building has occupants
        if (building.occupants && building.occupants.length > 0) {
          // Find the occupant with the matching build_living_space_uu_id
          const occupant = building.occupants.find(
            (occ: any) => occ.build_living_space_uu_id === userSelection
          );

          if (occupant) {
            objectUserSelection = {
              userType: "occupant",
              selected: {
                ...occupant,
                buildName: building.build_name,
                buildNo: building.build_no,
              },
            };
            break;
          }
        }
      }
    }
  }
  return {
    ...objectUserSelection,
  };
}

// const avatarInfo = await retrieveAvatarInfo();
// lang: avatarInfo?.data?.lang
//   ? String(avatarInfo?.data?.lang).toLowerCase()
//   : undefined,
// avatar: avatarInfo?.data?.avatar,
// fullName: avatarInfo?.data?.full_name,
// async function retrieveAvatarInfo() {
//   const response = await fetchDataWithToken(
//     `${baseUrlAuth}/authentication/avatar`,
//     {},
//     "POST"
//   );
//   return response;
// }

export {
  checkAccessTokenIsValid,
  retrieveAccessToken,
  retrieveUserType,
  retrieveAccessObjects,
  retrieveUserSelection,
  retrieveApplicationbyUrl,
  retrievePageList,
  // retrieveavailablePages,
};
