// pages/api/admin/returns/[id].js
import { apiHandler, db } from "@/helpers/api";

export default apiHandler({
	get: getReturnDetails,
});

async function getReturnDetails(req, res) {
	const userID = req.userID;
	const { id } = req.query;

	if (!db.initialized) await db.initialize();

	try {
		const userData = await db.User.findByPk(userID);

		if (!userData) return res.status(404).json({ error: "Unknown!" });

		if (userData.admin < 1) {
			return res.status(401).json({ error: "Unauthorized access." });
		}

		if (!id) {
			return res.status(400).json({ error: "ID retur este obligatoriu!" });
		}

		// Query pentru retur
		const returnRecord = await db.Returns.findByPk(id);

		if (!returnRecord) {
			return res.status(404).json({ error: "Returul nu există!" });
		}

		const returnData = returnRecord.toJSON();

		// Parse selectedItems
		let selectedItems = [];
		try {
			selectedItems = typeof returnData.selectedItems === "string" 
				? JSON.parse(returnData.selectedItems) 
				: returnData.selectedItems;
			
			if (typeof selectedItems === "string") {
				selectedItems = JSON.parse(selectedItems);
			}
		} catch (e) {
			console.error("Error parsing selectedItems:", e);
			selectedItems = [];
		}

		// Query separat pentru User
		let user = null;
		if (returnData.userID && returnData.userID > 0) {
			try {
				const userRecord = await db.User.findByPk(returnData.userID, {
					attributes: ["id", "email", "firstName", "lastName", "createdAt"],
				});
				user = userRecord ? userRecord.toJSON() : null;
			} catch (e) {
				console.error(`Error fetching user ${returnData.userID}:`, e.message);
				user = null;
			}
		}

		// Query separat pentru Order cu toate detaliile
		let order = null;
          console.log("RETURN DATA:" + returnData.orderID); 
		if (returnData.orderID) {
			try {
				const orderRecord = await db.Orders.findByPk(returnData.orderID);
                    console.log(orderRecord); 
				if (orderRecord) {
					order = orderRecord.toJSON();
					// Parse items
					try {
						order.items = typeof order.items === "string" 
							? JSON.parse(order.items) 
							: order.items;
					} catch (e) {
						order.items = [];
					}
				}
			} catch (e) {
				console.error(`Error fetching order ${returnData.orderID}:`, e.message);
				order = null;
			}
		}

		// Calculează produsele returnate și totalul
		let returnedProducts = [];
		let returnTotal = 0;
          
		if (order && order.items && selectedItems.length > 0) {
               
	
				order.items.forEach(itemId => { 
                         returnTotal += parseFloat(itemId.price) * parseInt(itemId.quantity);
                         
                    });
			
		}

		return res.status(200).json({
			return: {
				...returnData,
				selectedItems: selectedItems,
				user: user,
				order: order,
				returnedProducts: returnedProducts,
				returnTotal: returnTotal.toFixed(2)
			}
		});
	} catch (error) {
		console.error("Eroare la obținerea detaliilor returului:", error);
		return res.status(500).json({ error: "Eroare la obținerea detaliilor returului" });
	}
}