const express = require("express");
const { query } = require("../db");

const router = express.Router();
const UPSTREAM_API_KEY = process.env.UPSTREAM_API_KEY || "";

// GET /zapi/services — stock ពិតពី shopmailmmo.store
router.get("/", async (req, res) => {
  try {
    const services = await query("SELECT * FROM services");

    if (UPSTREAM_API_KEY && services.length > 0) {
      try {
        const response = await fetch("https://shopmailmmo.store/v1/api/fb_stock", {
          headers: { "api_key": UPSTREAM_API_KEY },
        });
        if (response.ok) {
          const data = await response.json();
          const stock = typeof data.stock === "number" ? data.stock : 0;
          // Update stock in DB
          await query("UPDATE services SET stock = ? WHERE id = ?", [stock, services[0].id]);
          services[0].stock = stock;
        }
      } catch (err) {
        // Use cached stock
      }
    }

    // Convert price to number
    res.json(services.map(s => ({ ...s, price: parseFloat(s.price), stock: s.stock })));
  } catch (err) {
    console.error("[Services]", err.message);
    res.json([]);
  }
});

module.exports = router;
