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

export default apiHandler({
	get: getAddresses,
	post: saveAddress,
	put: updateAddress,
	delete: deleteAddress,
});

async function getAddresses(req, res) {
	if (!db.initialized) await db.initialize();

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

     if (!userData) {
          return res.status(404).json({ success: false, error: "Utilizator necunoscut!" });
     }

     if (userData.id != userID) {
          return res.status(401).json({ success: false, error: "Neautorizat!" });
     }

	const addresses = await db.UserAddress.findAll({
		where: { userID: req.userID },
		order: [
			["isDefault", "DESC"],
			["createdAt", "DESC"],
		],
	});
	return res.status(200).json({ addresses });
}

async function saveAddress(req, res) {
	if (!db.initialized) await db.initialize();

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

     if (!userData) {
          return res.status(404).json({ success: false, error: "Utilizator necunoscut!" });
     }

     if (userData.id != userID) {
          return res.status(401).json({ success: false, error: "Neautorizat!" });
     }

	const count = await db.UserAddress.count({ where: { userID: req.userID } });
	if (count >= 5) return res.status(400).json({ error: "Poți salva maxim 5 adrese." });

	const address = await db.UserAddress.create({ ...req.body, userID: req.userID });
	return res.status(200).json({ success: true, address });
}

async function updateAddress(req, res) {
	if (!db.initialized) await db.initialize();

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

     if (!userData) {
          return res.status(404).json({ success: false, error: "Utilizator necunoscut!" });
     }

     if (userData.id != userID) {
          return res.status(401).json({ success: false, error: "Neautorizat!" });
     }

	const { id, setDefault, ...data } = req.body;

	const address = await db.UserAddress.findOne({ where: { id, userID: req.userID } });
	if (!address) return res.status(404).json({ error: "Adresa nu există." });

	if (setDefault) {
		await db.UserAddress.update({ isDefault: 0 }, { where: { userID: req.userID } });
		await address.update({ isDefault: 1 });
	} else {
		await address.update(data);
	}

	return res.status(200).json({ success: true });
}

async function deleteAddress(req, res) {
	if (!db.initialized) await db.initialize();

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

     if (!userData) {
          return res.status(404).json({ success: false, error: "Utilizator necunoscut!" });
     }

     if (userData.id != userID) {
          return res.status(401).json({ success: false, error: "Neautorizat!" });
     }

	const { id } = req.body;

	await db.UserAddress.destroy({ where: { id, userID: req.userID } });
	return res.status(200).json({ success: true });
}
