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

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

	try {
          const subcategoryName = req.query.name;

          const categoryExists = await db.Categories.findOne({
               attributes: ['id'], 
               where: {
                    url: subcategoryName, 
               },
               limit: 1,
          });
     
          if(!categoryExists) {
               return res.status(404).json('Unknown!');
          }

		const getSubcategoryChildrens = await db.Categories.findAll({
               where: { parentID: categoryExists.id },
               limit: 10,
               raw:false
          });

		return res.status(200).json({ childrens: getSubcategoryChildrens });
	} catch (error) {
		console.error("Error fetching categories:", error);
		return res
			.status(500)
			.json({ error: "Internal server error", status: 500 });
	}
}
