const express = require("express");
const router = express.Router();
const db = require("../models");
const { Op } = require("sequelize");

router.get("/", async (req, res) => {
  try {
    const variables = await db.variables.findAll();
    res.json({ success: true, data: variables });
  } catch (err) {
    res.status(500).json({ success: false, error: err.message });
  }
});

router.get("/:id", async (req, res) => {
  try {
    const variable = await db.variables.findByPk(req.params.id);
    if (!variable)
      return res
        .status(404)
        .json({ success: false, error: "Variable not found" });
    res.json({ success: true, data: variable });
  } catch (err) {
    res.status(500).json({ success: false, error: err.message });
  }
});

router.post("/:id", async (req, res) => {
  try {
    const variable = await db.variables.create(req.body);
    res.status(201).json({ success: true, data: variable });
  } catch (err) {
    res.status(400).json({ success: false, error: err.message });
  }
});

router.put("/:id", async (req, res) => {
  try {
    const [updated] = await db.variables.update(req.body, {
      where: { id: req.params.id },
    });
    if (!updated)
      return res
        .status(404)
        .json({ success: false, error: "Variable not found" });
    const variable = await db.variables.findByPk(req.params.id);
    res.json({ success: true, data: variable });
  } catch (err) {
    res.status(400).json({ success: false, error: err.message });
  }
});

router.delete("/:id", async (req, res) => {
  try {
    const deleted = await db.variables.destroy({
      where: { id: req.params.id },
    });
    if (!deleted)
      return res
        .status(404)
        .json({ success: false, error: "Variable not found" });
    res.json({ success: true, data: { message: "Variable deleted" } });
  } catch (err) {
    res.status(500).json({ success: false, error: err.message });
  }
});

module.exports = router;
