export const fetchLeafcutter = async (url: string, options: any) => {
  /*

    const headers = {
      'X-Opensearch-Username': process.env.OPENSEARCH_USER!,
      'X-Opensearch-Password': process.env.OPENSEARCH_PASSWORD!,
      'X-Leafcutter-User': token.email.toLowerCase()
    };
    */
  const fetchData = async (url: string, options: any) => {
    try {
      const res = await fetch(url, options);
      const json = await res.json();
      return json;
    } catch (error) {
      console.log({ error });
      return null;
    }
  };

  const data = await fetchData(url, options);
  console.log({ data });

  if (!data) {
    const csrfURL = `${process.env.NEXT_PUBLIC_LEAFCUTTER_URL}/api/auth/csrf`;
    const csrfData = await fetchData(csrfURL, {});
    console.log({ csrfData });
    const authURL = `${process.env.NEXT_PUBLIC_LEAFCUTTER_URL}/api/auth/callback/credentials`;
    const authData = await fetchData(authURL, { method: "POST" });
    console.log({ authData });
    if (!authData) {
      return null;
    } else {
      return await fetchData(url, options);
    }
  } else {
    return data;
  }
};


