import express from "express";
import { query } from "../db.js";

const router = express.Router();

router.get("/", async (_req, res) => {
  try {
    const rows = await query(
      "SELECT state_json FROM app_state WHERE state_key = ? LIMIT 1",
      ["main"]
    );

    if (!rows.length) {
      return res.json({ ok: true, state: null });
    }

    let state = null;
    try {
      state = JSON.parse(rows[0].state_json || "{}");
    } catch {
      state = null;
    }

    return res.json({ ok: true, state });
  } catch (error) {
    console.error(error);
    return res.status(500).json({ ok: false, error: "Failed to load app state" });
  }
});

router.put("/", async (req, res) => {
  try {
    const state = req.body?.state ?? {};
    const stateJson = JSON.stringify(state);

    await query(
      `INSERT INTO app_state (state_key, state_json)
       VALUES (?, ?)
       ON DUPLICATE KEY UPDATE state_json = VALUES(state_json), updated_at = CURRENT_TIMESTAMP`,
      ["main", stateJson]
    );

    return res.json({ ok: true });
  } catch (error) {
    console.error(error);
    return res.status(500).json({ ok: false, error: "Failed to save app state" });
  }
});

export default router;
