import { db } from "@/helpers/api/db";

export default async function handler(req, res) {
	if (!db.initialized) {
		await db.initialize();
	}

	try {
		const getParentsWithChildren = 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 
          });
     
		return res.status(200).json({ categories: getParentsWithChildren });
	} catch (error) {
		console.error("Error fetching categories:", error);
		return res
			.status(500)
			.json({ error: "Internal server error", status: 500 });
	}
}
