import express from "express";
import fs from "fs";
import path from "path";
import { fileURLToPath } from "url";
import cors from "cors";

const __dirname = path.dirname(fileURLToPath(import.meta.url));
const app = express();
const DATA_PATH = path.join(__dirname, "public", "data.json");

app.use(cors());
app.use(express.json({ limit: "10mb" }));

app.get("/api/data", (req, res) => {
  const raw = fs.readFileSync(DATA_PATH, "utf-8");
  res.json(JSON.parse(raw));
});

app.post("/api/data", (req, res) => {
  try {
    fs.writeFileSync(DATA_PATH, JSON.stringify(req.body, null, 2), "utf-8");
    res.json({ ok: true });
  } catch (e) {
    res.status(500).json({ ok: false, error: e.message });
  }
});

app.listen(4000, () => console.log("API running on :4000"));