import { prisma } from "@/lib/prisma";

export async function getCategoryWithProducts(slug: string, brandSlug?: string) {
  const category = await prisma.category.findUnique({
    where: { slug, isActive: true },
    include: { 
      children: {
        where: { isActive: true },
        select: { id: true }
      }
    },
  });

  if (!category) return null;

  // Include both the category and its children IDs
  const categoryIds = [category.id, ...category.children.map(c => c.id)];

  const products = await prisma.product.findMany({
    where: {
      categoryId: { in: categoryIds },
      isActive: true,
      ...(brandSlug ? { brand: { slug: brandSlug } } : {}),
    },
    include: { 
      images: true, 
      brand: true,
      variants: true,
    },
    orderBy: { createdAt: "desc" },
  });

  return { category, products };
}