import { apiHandler, db } from "@/helpers/api";
import { Op } from "sequelize";

export default apiHandler({
	get: getProducts,
	post: createProduct,
});

async function getProducts(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 { search, category, page = 1, limit = 50 } = req.query;
		const offset = (page - 1) * limit;

		const where = {};

		if (search) {
			where[Op.or] = [
				{ name: { [Op.like]: `%${search}%` } },
				{ sku: { [Op.like]: `%${search}%` } },
				{ ean: { [Op.like]: `%${search}%` } },
			];
		}

		if (category) {
			where.categorySlug = category;
		}

		const { count, rows } = await db.Products.findAndCountAll({
			where,
			limit: parseInt(limit),
			offset: parseInt(offset),
			order: [["id", "DESC"]],
		});

		return res.status(200).json({
			products: rows,
			total: count,
			page: parseInt(page),
			totalPages: Math.ceil(count / limit),
		});
	} catch (error) {
		console.error("Eroare la preluarea produselor:", error);
		return res.status(500).json({ error: "Eroare la preluarea produselor" });
	}
}

async function createProduct(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 productData = req.body;

		const newProduct = await db.Products.create({
			...productData,
			createdAt: new Date(),
			updatedAt: new Date(),
		});

		return res.status(201).json({
			success: true,
			product: newProduct,
			message: "Produs creat cu succes!",
		});
	} catch (error) {
		console.error("Eroare la crearea produsului:", error);
		return res.status(500).json({ error: "Eroare la crearea produsului" });
	}
}
