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

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

async function getReturns(req, res) {
	const userID = req.userID;
	const { page = 1, limit = 10, status, search } = 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." });
		}

		const { Op } = require("sequelize");

		let whereClause = {};

		// Filtrare după status
		if (status && status !== "all") {
			whereClause.status = status;
		}

		// Căutare
		if (search) {
			whereClause[Op.or] = [
				{ orderID: { [Op.like]: `%${search}%` } },
				{ reason: { [Op.like]: `%${search}%` } },
				{ accountName: { [Op.like]: `%${search}%` } }
			];
		}

		const offset = (parseInt(page) - 1) * parseInt(limit);

		// Query pentru retururi
		const returns = await db.Returns.findAll({
			where: whereClause,
			order: [["id", "DESC"]],
			limit: parseInt(limit),
			offset: offset,
		});

		// Query separat pentru count
		const count = await db.Returns.count({
			where: whereClause,
		});

		// Procesare date retururi
		const processedReturns = await Promise.all(
			returns.map(async (returnItem) => {
				const returnData = returnItem.toJSON();

				// Parse selectedItems din JSON
				let selectedItems = [];
				try {
					selectedItems = typeof returnData.selectedItems === "string" 
						? JSON.parse(returnData.selectedItems) 
						: returnData.selectedItems;
					
					// Dacă e string în JSON (ca în exemplu: "\"[1168]\"")
					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"],
						});
						user = userRecord ? userRecord.toJSON() : null;
					} catch (e) {
						console.error(`Error fetching user ${returnData.userID}:`, e.message);
						user = null;
					}
				}

				// Query separat pentru Order
				let order = null;
				if (returnData.orderID) {
					try {
						const orderRecord = await db.Orders.findByPk(returnData.orderID);
						if (orderRecord) {
							const orderJson = orderRecord.toJSON();
							// Parse items
							let items = [];
							try {
								items = typeof orderJson.items === "string" 
									? JSON.parse(orderJson.items) 
									: orderJson.items;
							} catch (e) {
								items = [];
							}
							order = {
								id: orderJson.id,
								status: orderJson.status,
								items: items,
								billingType: orderJson.billingType,
								customerName: orderJson.billingType === 0 
									? `${orderJson.pf_prenume} ${orderJson.pf_nume_familie}`
									: orderJson.pj_nume_firma,
								customerEmail: orderJson.billingType === 0 
									? orderJson.pf_email 
									: orderJson.pj_email
							};
						}
					} catch (e) {
						console.error(`Error fetching order ${returnData.orderID}:`, e.message);
						order = null;
					}
				}

				// Calculează totalul returului
				let returnTotal = 0;
                 
				if (order && order.items && selectedItems.length > 0) {
					order.items.forEach(itemId => { 
                              returnTotal += parseFloat(itemId.price) * parseInt(itemId.quantity);
						
					});
				}

				return {
					id: returnData.id,
					userID: returnData.userID,
					orderID: returnData.orderID,
					selectedItems: selectedItems,
					reason: returnData.reason,
					details: returnData.details,
					refundMethod: returnData.refundMethod,
					iban: returnData.iban,
					accountName: returnData.accountName,
					returnMethod: returnData.returnMethod,
					status: returnData.status || "pending",
					createdAt: returnData.createdAt,
					updatedAt: returnData.updatedAt,
					user: user,
					order: order,
					returnTotal: returnTotal.toFixed(2)
				};
			})
		);

		const totalPages = Math.ceil(count / parseInt(limit));

		return res.status(200).json({
			returns: processedReturns,
			pagination: {
				currentPage: parseInt(page),
				totalPages,
				totalItems: count,
				itemsPerPage: parseInt(limit),
			},
		});
	} catch (error) {
		console.error("Eroare la obținerea retururilor:", error);
		return res.status(500).json({ error: "Eroare la obținerea retururilor" });
	}
}