var express = require("express");
var router = express.Router();
const { exec } = require("child_process");

/* GET home page. */
router.get("/", function (req, res, next) {
  res.render("index", { title: "Express" });
});

router.get("/products", function (req, res, next) {
  // Use curl to fetch products from Shopify
  const curlCmd = `curl -X GET \"https://roving-house.myshopify.com/admin/api/2021-07/products.json\" -u 65c3c809c002379e3a0ea04aeaf2cf84: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`;
  exec(curlCmd, (error, stdout, stderr) => {
    if (error) {
      return res.render("products", { products: [], error: error.message });
    }
    let products = [];
    console.log(error, stdout);
    try {
      const data = JSON.parse(stdout);
      products = data.products || [];
    } catch (e) {
      return res.render("products", {
        products: [],
        error: "Failed to parse products",
      });
    }
    res.render("products", { products });
  });
});

module.exports = router;
