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

const availableEventsURL = `${baseUrl}/access/endpoints/available`;

async function setAvailableEvents() {
  const cookieStore = await cookies();
  const nextCrypto = new NextCrypto(tokenSecret);

  const availableResponse: any = await fetchDataWithToken(
    availableEventsURL,
    {},
    "POST",
    false
  );

  if (availableResponse.status === 200) {
    const availableEventData = Array.from(availableResponse?.result) || [];
    const availableEvents = await nextCrypto.encrypt(
      JSON.stringify({ availableEvents: availableEventData })
    );
    cookieStore.set({
      name: "availableEvents",
      value: availableEvents,
      ...cookieObject,
    });
  }
}

export { setAvailableEvents };
