"use server";
import { fetchDataWithToken } from "../api-fetcher";
import { cookies } from "next/headers";
import { baseUrl } from "../basics";

const logOutEndpoint = `${baseUrl}/authentication/logout`;
const logOutAllEndpoint = `${baseUrl}/authentication/disconnect`;

interface LoginOutUser {
  domain: string;
}

async function logoutActiveSession(payload: LoginOutUser) {
  "use server";
  const cookieStore = await cookies();
  cookieStore.delete("accessToken");
  cookieStore.delete("accessObject");
  cookieStore.delete("userProfile");
  cookieStore.delete("userSelection");

  const tokenResponse: any = await fetchDataWithToken(
    logOutEndpoint,
    {
      domain: payload.domain,
    },
    "POST",
    false
  );
  if (tokenResponse.status === 200) {
    return true;
  }
  return false;
}

async function logoutAllSessions(payload: LoginOutUser) {
  const cookieStore = await cookies();
  cookieStore.delete("accessToken");
  cookieStore.delete("accessObject");
  cookieStore.delete("userProfile");
  cookieStore.delete("userSelection");
  const tokenResponse: any = await fetchDataWithToken(
    logOutAllEndpoint,
    {
      domain: payload.domain,
    },
    "POST",
    false
  );
  if (tokenResponse.status === 200) {
    return true;
  }
  return false;
}

export { logoutActiveSession, logoutAllSessions };
