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

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

async function getReturnsStats(req, res) {
	const userID = req.userID;

	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");

		// Total retururi active (pending, approved, processing)
		const activeReturns = await db.Returns.count({
			where: {
				status: {
					[Op.in]: ['pending', 'approved', 'processing']
				}
			}
		});

		// Retururi în așteptare
		const pendingReturns = await db.Returns.count({
			where: {
				status: 'pending'
			}
		});

		// Retururi finalizate luna aceasta
		const startOfMonth = new Date();
		startOfMonth.setDate(1);
		startOfMonth.setHours(0, 0, 0, 0);

		const completedThisMonth = await db.Returns.count({
			where: {
				status: 'completed',
				updatedAt: {
					[Op.gte]: startOfMonth
				}
			}
		});

		// Total retururi
		const totalReturns = await db.Returns.count();

		// Retururi aprobate
		const approvedReturns = await db.Returns.count({
			where: {
				status: 'approved'
			}
		});

		// Retururi respinse
		const rejectedReturns = await db.Returns.count({
			where: {
				status: 'rejected'
			}
		});

		return res.status(200).json({
			stats: {
				activeReturns,
				pendingReturns,
				completedThisMonth,
				totalReturns,
				approvedReturns,
				rejectedReturns
			}
		});
	} catch (error) {
		console.error("Eroare la obținerea statisticilor retururilor:", error);
		return res.status(500).json({ error: "Eroare la obținerea statisticilor" });
	}
}