import { HomeContent } from "@/components/home";
import type { Category } from "@/components/tutorials";
import { getAllTutorials } from "@/lib/tutorials";
import type { Metadata } from "next";

export const metadata: Metadata = {
    title: "Tutos | Jessy David",
    description: "Mes tutoriels",
};

export const dynamic = "force-dynamic";

function extractCategories(
    tutorials: Awaited<ReturnType<typeof getAllTutorials>>
): Category[] {
    const categoriesMap = new Map<string, Category>();
    tutorials.forEach((t) => {
        if (!categoriesMap.has(t.category.id)) {
            categoriesMap.set(t.category.id, {
                id: t.category.id,
                name: t.category.name,
                color: t.category.color,
            });
        }
    });
    return Array.from(categoriesMap.values());
}

export default async function HomePage({
    searchParams,
}: {
    searchParams: Promise<{ category?: string }>;
}) {
    const { category } = await searchParams;
    const allTutorials = await getAllTutorials();
    const categories = extractCategories(allTutorials);

    const tutorials = category
        ? allTutorials.filter((t) => t.category.id === category)
        : allTutorials.slice(0, 4);

    return (
        <HomeContent
            tutorials={tutorials}
            categories={categories}
            allTutorialsCount={allTutorials.length}
        />
    );
}
