import { Book, Chapter, Editor } from "./types";

const API_URL = process.env.NEXT_PUBLIC_API_URL as string;
const API_TOKEN = process.env.STRAPI_API_TOKEN as string;

/**
 * Centralized API fetch function with TypeScript support.
 * Handles GET, POST, PUT, DELETE methods and includes headers by default.
 */
export async function fetchFromAPI<T>(
  endpoint: string,
  options: RequestInit = {}
): Promise<T> {
  const url = `${API_URL}${endpoint}`;

  const headers: HeadersInit = {
    Authorization: `Bearer ${API_TOKEN}`,
    "Content-Type": "application/json",
  };

  const config: RequestInit = {
    method: "GET", // Default method is GET
    headers,
    ...options,
  };

  try {
    const response = await fetch(url, config);
    if (!response.ok) {
      const errorData = await response.json();
      console.error(`Error fetching ${url}:`, errorData);
      throw new Error(errorData.message || `API fetch error (status: ${response.status})`);
    }
    const responseJson = await response.json();
    console.log(responseJson) 
    return responseJson;
  } catch (error) {
    console.error("Fetch error:", error);
    throw error;
  }
}

/**
 * Fetches all books from the API.
 * Populates optional fields like Chapters or Editors based on requirements.
 */
export async function fetchBooks(): Promise<Book[]> {
  const data = await fetchFromAPI<{ data: Book[] }>("/api/books?populate=*");
  return data.data;
}

export async function fetchBookChapterLinks(bookId: string): Promise<Book> {
  const currentDateTime = new Date().toISOString();
  const data = await fetchFromAPI<{ data: Book }>(`/api/books/${bookId}?populate[chapters][filters][release_datetime][$lte]=${currentDateTime}`);
  return data.data
}

/**
 * Fetches a specific book by ID with its chapters.
 * Filters chapters by release date to include only valid ones.
 */
export async function fetchBookById(bookId: string): Promise<Book> {
  const currentDateTime = new Date().toISOString();
  const data = await fetchFromAPI<{ data: Book }>(
    `/api/books/${bookId}?populate[chapters][filters][release_datetime][$lte]=${currentDateTime}&populate=cover`
  );
  return data.data;
}

/**
 * Fetches a specific chapter by ID.
 */
export async function fetchChapterById(chapterId: string): Promise<Chapter> {
  const data = await fetchFromAPI<{ data: Chapter }>(`/api/chapters/${chapterId}?populate[book][fields]=documentId`);
  return data.data;
}

/**
 * Fetches all editors.
 */
export async function fetchEditors(): Promise<Editor[]> {
  const data = await fetchFromAPI<{ data: Editor[] }>("/api/editors");
  return data.data;
}