/** @module api/fetcher
 * @param {string} url - The url to fetch
 * @param {RequestInit} options - The fetch options
 * @returns {Promise<T>} - The fetched data
 * @throws {string} - The error message
 * Fetches the data from the given url with the given options *
 * @hidden
 */

// import { headers } from "next/headers";

export default async function fetcher<T>(
  url: string,
  options?: RequestInit,
  showStrapiMetadata?: boolean
): Promise<T> {
  const isSSR = typeof window === 'undefined';
  const reqUrl = isSSR ? `${process.env.NEXT_PUBLIC_API_URL}${url}` : `/api/${url}`;
  const printResponseInConsole =
    false && process.env.NODE_ENV === 'development';



  try {
    const headers = options?.headers || {};
    const response = await fetch(reqUrl, {
      next: { revalidate: false },
      ...options,
      headers: {
        Authorization: `Bearer ${process.env.NEXT_API_TOKEN}`,
        ...headers
      }
    });
    const json = await response.json();
    if (response.ok) {
      const response = showStrapiMetadata
        ? (json as Promise<T>)
        : (json.data as Promise<T>);

      if (printResponseInConsole) {
        print.success(reqUrl, response);
      } else {
        print.success(reqUrl);
      }
      return response;
    } else {
      throw json;
    }
  } catch (error) {
          console.log('3')
    print.error(reqUrl, error);
    throw 'Error fetching data from API';
  }
}

const print = {
  error: (url: string, error: any) => {
    console.log('============================');
    console.log(`\x1b[31mAPI Error:\x1b[0m ${url}\n`, error);
  },
  success: (url: string, data?: any) => {
    console.log('============================');
    console.log(`\x1b[32mReceived:\x1b[0m ${url}`);
    if (data) {
      console.log(data);
    }
  },
  info: (url: string) => {
    console.log('============================');
    console.log(`\x1b[34mRequesting:\x1b[0m ${url}`);
  }
};
