import Features from "@/components/common/Features";
import Hero from "@/components/homes/home-6/Hero";
import React from "react";
import CategoryProducts from "@/components/common/CategoryProducts";
import { db } from "@/helpers/api";

export const metadata = {
	title: "Home 6 || Ecomus - Ultimate Nextjs Ecommerce Template",
	description: "Ecomus - Ultimate Nextjs Ecommerce Template",
};

async function fetchCategoriesWithProducts() {
     if (!db.initialized)
          await db.initialize(); 

	const categories = await db.Categories.findAll({
		where: { parentID: 0 },
		include: [
			{
				model: db.Categories,
				as: "children",
				include: [
					{
						model: db.Categories,
						as: "subChildren",
						required: false,
					},
				],
				required: false,
			},
		],
		raw: false,
	});

	const categoriesWithProducts = await Promise.all(
		categories.map(async (category) => {
			const products = await db.Products.findAll({
				where: { categorySlug: category.slug },
				limit: 12,
			});
			return {
				...category.toJSON(),
				products: products.map((product) => product.toJSON()),
			};
		})
	);

	return categoriesWithProducts;
}

export default async function Page() {
     if (!db.initialized)
          await db.initialize(); 
     
	const categoriesWithProducts = await fetchCategoriesWithProducts();

	return (
		<>
			<Hero />
			{categoriesWithProducts.map((category) => (
				<CategoryProducts key={category.slug} category={category} />
			))}
			<div className='mt-5'></div>
			<Features />
			<div className='mt-5'></div>
		</>
	);
}
