import BookPoster from "@/components/BookPoster";
import db from "../../db";
import { Book } from "./../../types";

// refresh cache every 24 hours
export const revalidate = 60 * 60 * 24;

export default async function Home() {
  const books = db.collection("books");

  const allBooks = (await books
    .find(
      {},
      {
        projection: { $vector: 1 },
      }
    )
    .toArray()) as Book[];

  // Deduplicate the results
  const seenIds = new Set();
  const deduplicatedBooks = allBooks.filter((book) => {
    if (seenIds.has(book?.Book_Title)) {
      return false; // Skip duplicate
    }
    seenIds.add(book?.Book_Title);
    return true; // Keep unique book
  });

  return (
    <div className="flex items-center justify-center pb-24 pt-16">
      <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-10">
        {deduplicatedBooks.map((book) => (
          <BookPoster key={book._id} book={book} />
        ))}
      </div>
    </div>
  );
}

// using mistralai api key
// export async function embedding(prompt: string) {
//   const response = await fetch("https://api.mistral.ai/v1/embeddings", {
//     method: "POST",
//     headers: {
//       "Content-Type": "application/json",
//       Authorization: `Bearer ${process.env.MISTRALAI_API_KEY}`,
//     },
//     body: JSON.stringify({
//       input: [prompt], // Mistral expects an array of inputs
//       model: "mistral-embed",
//     }),
//   });

//   if (!response.ok) {
//     const errorDetails = await response.json();
//     throw new Error(`Error: ${response.status} - ${errorDetails.message}`);
//   }

//   const result = await response.json();
//   return result.data[0].embedding;
// }
