import { getServerSession } from "app/_lib/authentication";
import { cookies } from "next/headers";

const getHeaders = async () => {
  const allCookies = cookies().getAll();
  const session = await getServerSession();
  const headers = {
    "Content-Type": "application/json",
    Accept: "application/json",
    "X-Browser-Fingerprint": `${session.expires}`,
    // @ts-ignore
    "X-CSRF-Token": session.user.zammadCsrfToken,
    Cookie: allCookies
      .map((cookie: any) => `${cookie.name}=${cookie.value}`)
      .join("; "),
  };

  return headers;
};

interface ExecuteGraphQLOptions {
  query: string;
  variables?: Record<string, any>;
}

export const executeGraphQL = async ({
  query,
  variables,
}: ExecuteGraphQLOptions): Promise<any> => {
  const headers = await getHeaders();
  const endpoint = `${process.env.ZAMMAD_URL}/graphql`;
  const body = JSON.stringify({ query, ...(variables && { variables }) });
  const result = await fetch(endpoint, {
    headers,
    body,
    method: "POST",
    next: { revalidate: 0 },
  });

  const { data, errors } = await result.json();

  if (result.status !== 200) {
    throw new Error(`Error: ${result.status}`);
  } else if (errors) {
    throw new Error(`Error: ${JSON.stringify(errors)}`);
  }

  return data;
};

interface ExecuteRESTOptions {
  path: string;
}

export const executeREST = async ({
  path,
}: ExecuteRESTOptions): Promise<any> => {
  const headers = await getHeaders();
  const result = await fetch(`${process.env.ZAMMAD_URL}${path}`, {
    method: "GET",
    headers,
  });

  if (result.status !== 200) {
    throw new Error(`Error: ${result.status}`);
  }

  return await result.json();
};
