"use server";
import { fetchDataWithToken, fetchData } from "../api-fetcher";
import { baseUrl, tokenSecret } from "../basics";
import { cookies } from "next/headers";
import NextCrypto from "next-crypto";

const checkToken = `${baseUrl}/authentication/valid`;
const nextCrypto = new NextCrypto(tokenSecret);

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

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?.user_type : 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 retrieveAvailableEvents() {
  const cookieStore = await cookies();
  const encrpytAccessObject = cookieStore.get("availableEvents")?.value || "";
  const decrpytAccessObject = await nextCrypto.decrypt(encrpytAccessObject);
  return decrpytAccessObject ? JSON.parse(decrpytAccessObject) : null;
}

async function retrieveAvatarInfo() {
  const response = await fetchDataWithToken(
    `${baseUrl}/authentication/avatar`,
    {},
    "POST"
  );
  return response;
}

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;
    console.log("occupants", 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}`,
      };
    }
  }
  const avatarInfo = await retrieveAvatarInfo();
  return {
    ...objectUserSelection,
    lang: avatarInfo?.data?.lang
      ? String(avatarInfo?.data?.lang).toLowerCase()
      : undefined,
    avatar: avatarInfo?.data?.avatar,
    fullName: avatarInfo?.data?.full_name,
  };
}

export {
  checkAccessTokenIsValid,
  retrieveAccessToken,
  retrieveUserType,
  retrieveAccessObjects,
  retrieveAvailableEvents,
  retrieveUserSelection,
};
