const express = require("express");
const router = express.Router();
const db = require("../models");

// Helper to cast value to type
function castToType(value, type) {
  if (type === "INTEGER") return parseInt(value, 10);
  if (type === "FLOAT") return parseFloat(value);
  if (type === "STRING") return String(value);
  return value;
}

// Helper to safely evaluate condition
function safeEval(condition, context) {
  // Only allow access to context variables
  return Function(
    ...Object.keys(context),
    `return (${condition});`
  )(...Object.values(context));
}

router.get("/", async (req, res) => {
  try {
    const { variable } = req.query;
    if (!variable) {
      return res
        .status(400)
        .json({ success: false, error: "Missing variable parameter" });
    }
    // Decode base64
    let decoded;
    try {
      decoded = Buffer.from(variable, "base64").toString("utf-8");
    } catch (e) {
      return res
        .status(400)
        .json({ success: false, error: "Invalid base64 encoding" });
    }
    let payload;
    try {
      payload = JSON.parse(decoded);
    } catch (e) {
      return res
        .status(400)
        .json({ success: false, error: "Invalid JSON in variable payload" });
    }

    // Fetch all variables and rules
    const [dbVariables, rules] = await Promise.all([
      db.variables.findAll(),
      db.rules.findAll(),
    ]);

    // Build a map of variable types
    const variableTypeMap = {};
    dbVariables.forEach((v) => {
      variableTypeMap[v.name] = v.type;
    });

    // Prepare context for evaluation: only include variables that exist in db
    const context = {};
    for (const [key, value] of Object.entries(payload)) {
      if (variableTypeMap[key]) {
        context[key] = castToType(value, variableTypeMap[key]);
      }
    }

    // Evaluate each rule
    const results = [];
    for (const rule of rules) {
      let passed = false;
      try {
        passed = safeEval(rule.condition, context);
      } catch (e) {
        // Ignore rules with invalid conditions or missing variables
        continue;
      }
      if (passed) {
        results.push({ rule_id: rule.id, result: rule.action });
      }
    }

    return res.json({ success: true, data: results });
  } catch (err) {
    return res.status(500).json({ success: false, error: err.message });
  }
});

module.exports = router;
