import NextCrypto from "next-crypto";

import { fetchDataWithToken } from "@/apifetchers/api-fetcher";
import { baseUrlAuth, baseUrlRestriction, tokenSecret } from "@/apifetchers/basics";
import { cookies } from "next/headers";
import { AuthError } from "@/types/mutual/context/validations";

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

const nextCrypto = new NextCrypto(tokenSecret);

function fetchResponseStatus(response: any) {
  return 199 < response?.status && response?.status < 300;
}

async function checkAccessTokenIsValid() {
  try {
    const response = await fetchDataWithToken(checkToken, {}, "GET", false);
    return fetchResponseStatus(response);
  } catch (error) { throw new AuthError("No access token found") }
}

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

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

async function retrieveAccessToken() {
  const cookieStore = await cookies();
  try {
    const encrpytAccessToken = cookieStore.get("eys-zzz")?.value || "";
    return await nextCrypto.decrypt(encrpytAccessToken) || "";
  }
  catch (error) { throw new AuthError("No access token found") }
}

async function retrieveAccessObjects() {
  const cookieStore = await cookies();
  try {
    const encrpytAccessObject = cookieStore.get("eys-yyy")?.value || "";
    return await nextCrypto.decrypt(encrpytAccessObject) || "";
  }
  catch (error) { throw new AuthError("No access objects found") }
}

export {
  checkAccessTokenIsValid,
  retrieveAccessToken,
  retrieveAccessObjects,
  retrieveApplicationbyUrl,
  retrievePageList,
};
