"use server";
import { fetchDataWithToken } from "../api-fetcher";
import { baseUrlAuth, tokenSecret } from "../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 = await fetchDataWithToken(siteUrls, {}, "GET", false);
  return response?.status === 200 || response?.status === 202
    ? response.data?.sites
    : null;
}


async function retrievePagebyUrl(pageUrl: string) {

  const response = 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 decrpytUserSelection: any = await nextCrypto.decrypt(
    encrpytUserSelection
  );
  decrpytUserSelection = decrpytUserSelection
    ? JSON.parse(decrpytUserSelection)
    : null;

  const userSelection = decrpytUserSelection?.company_uu_id;

  let objectUserSelection = {};

  if (decrpytUserSelection?.user_type === "employee") {
    const accessObjects = (await retrieveAccessObjects()) || {};
    const companyList = accessObjects?.companies_list;
    const selectedCompany = companyList.find(
      (company: any) => company.uu_id === userSelection
    );
    if (selectedCompany) {
      objectUserSelection = {
        occupantName: `${selectedCompany?.public_name}`,
      };
    }
  } else if (decrpytUserSelection?.user_type === "occupant") {
    const buildPartUUID = userSelection?.build_part_uu_id;
    const occupantUUID = userSelection?.occupant_uu_id;
    const build_id = userSelection?.build_id;
    const accessObjects = (await retrieveAccessObjects()) || {};
    const availableOccupants = accessObjects?.available_occupants[build_id];
    const buildName = availableOccupants?.build_name;
    const buildNo = availableOccupants?.build_no;
    let selectedOccupant: any = null;
    const occupants = availableOccupants?.occupants;
    if (occupants) {
      selectedOccupant = occupants.find(
        (occupant: any) =>
          occupant.part_uu_id === buildPartUUID &&
          occupant.uu_id === occupantUUID
      );
    }
    if (selectedOccupant) {
      objectUserSelection = {
        buildName: `${buildName} - No:${buildNo}`,
        occupantName: `${selectedOccupant?.description} ${selectedOccupant?.part_name}`,
      };
    }
  }
  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,
  retrievePagebyUrl,
  retrievePageList,
  // retrieveavailablePages,
};
