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

export default apiHandler({
     put: updateSetting,
});

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

     try {
          const userID = req.userID; 
          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 { id } = req.query;
          const { value } = req.body;

          const setting = await db.Settings.findByPk(id);

          if (!setting) {
               return res.status(404).json({ error: "Setarea nu a fost găsită" });
          }

          setting.value = value;
          await setting.save();

          res.json({ success: true, setting });
     } catch (error) {
          res.status(500).json({ error: error.message });
     }
}