const express = require("express");
const fs = require("fs");

const app = express();
const PORT = 3000;
const DATA_FILE = "./data.json";

// Helper: read data
function readData() {
  return JSON.parse(fs.readFileSync(DATA_FILE, "utf8"));
}

// Helper: write data
function writeData(data) {
  fs.writeFileSync(DATA_FILE, JSON.stringify(data, null, 2));
}

// ============================
// GET /api/data → read values
// ============================
app.get("/data", (req, res) => {
  try {
    const data = readData();
    res.json(data);
  } catch (err) {
    res.status(500).json({ error: "Gagal membaca data" });
  }
});

// ============================
// ADD SENSOR
// ============================
app.post("/addSensor", (req, res) => {
  const { id } = req.body;

  if (!id) {
    return res.status(400).json({
      error: "Sensor ID is required"
    });
  }

  const sql = `INSERT INTO sensor_data (id) VALUES (?)`;

  db.query(sql, [id], (err, result) => {
    if (err) {
      console.error(err);

      // handle duplicate ID (optional but nice)
      if (err.code === "ER_DUP_ENTRY") {
        return res.status(400).json({
          error: "Sensor already exists"
        });
      }

      return res.status(500).json({ error: "DB error" });
    }

    res.json({
      message: "Sensor added successfully",
      id: id
    });
  });
});

// ===========================================
// GET /api/update?co2=&co=&bz=&aq=
// ===========================================
app.get("/update", (req, res) => {
  const { co2, co, bz, aq } = req.query;

  if (!co2 || !co || !bz || !aq) {
    return res.status(400).json({
      error: "Parameter wajib: co2, co, bz, aq"
    });
  }

  const newData = {
    CO2: Number(co2),
    CO: Number(co),
    BZ: Number(bz),
    AQ: Number(aq),
    updated_at: new Date().toISOString()
  };

  try {
    writeData(newData);
    res.json({
      message: "Data berhasil diperbarui",
      data: newData
    });
  } catch (err) {
    res.status(500).json({ error: "Gagal menyimpan data" });
  }
});

app.listen(PORT, () => {
  console.log(`API berjalan di port ${PORT}`);
});
