"use strict";
const { Router } = require("express");
const { query } = require("../db");
const router = Router();

function mapSettings(r) {
  if (!r) return null;
  return {
    id: r.id, name: r.name, motto: r.motto, address: r.address, phone: r.phone, email: r.email,
    logoUrl: r.logo_url, primaryColor: r.primary_color, currency: r.currency,
    gradingScale: r.grading_scale, termName: r.term_name, sessionName: r.session_name,
    principalName: r.principal_name, nextTermBegins: r.next_term_begins,
    updatedAt: r.updated_at ? new Date(r.updated_at).toISOString() : null,
  };
}

router.get("/settings/school", async (_req, res) => {
  const [row] = await query("SELECT * FROM school_settings LIMIT 1");
  if (!row) return res.status(404).json({ error: "Not initialized" });
  res.json(mapSettings(row));
});

router.patch("/settings/school", async (req, res) => {
  const [existing] = await query("SELECT id FROM school_settings LIMIT 1");
  if (!existing) return res.status(404).json({ error: "Not initialized" });
  const allowed = ["name", "motto", "address", "phone", "email", "logo_url", "primary_color", "currency", "grading_scale", "term_name", "session_name", "principal_name", "next_term_begins"];
  const keyMap = { logoUrl: "logo_url", primaryColor: "primary_color", gradingScale: "grading_scale", termName: "term_name", sessionName: "session_name", principalName: "principal_name", nextTermBegins: "next_term_begins" };
  const sets = []; const vals = [];
  for (const [k, v] of Object.entries(req.body || {})) {
    const col = keyMap[k] || k;
    if (allowed.includes(col)) { sets.push(`${col} = ?`); vals.push(v); }
  }
  if (!sets.length) return res.status(400).json({ error: "Nothing to update" });
  vals.push(existing.id);
  await query(`UPDATE school_settings SET ${sets.join(", ")} WHERE id = ?`, vals);
  const [row] = await query("SELECT * FROM school_settings WHERE id = ?", [existing.id]);
  res.json(mapSettings(row));
});

router.get("/settings/system", async (_req, res) => {
  const [row] = await query("SELECT * FROM system_status LIMIT 1");
  if (!row) return res.status(404).json({ error: "Not initialized" });
  res.json({ locked: !!row.locked, maintenanceMessage: row.maintenance_message, version: row.version, lastUpdated: row.last_updated ? new Date(row.last_updated).toISOString() : null });
});

router.patch("/settings/system", async (req, res) => {
  const [existing] = await query("SELECT id FROM system_status LIMIT 1");
  if (!existing) return res.status(404).json({ error: "Not initialized" });
  const { locked, maintenanceMessage, version } = req.body || {};
  const sets = []; const vals = [];
  if (locked !== undefined) { sets.push("locked = ?"); vals.push(locked ? 1 : 0); }
  if (maintenanceMessage !== undefined) { sets.push("maintenance_message = ?"); vals.push(maintenanceMessage); }
  if (version !== undefined) { sets.push("version = ?"); vals.push(version); }
  if (!sets.length) return res.status(400).json({ error: "Nothing to update" });
  vals.push(existing.id);
  await query(`UPDATE system_status SET ${sets.join(", ")} WHERE id = ?`, vals);
  const [row] = await query("SELECT * FROM system_status WHERE id = ?", [existing.id]);
  res.json({ locked: !!row.locked, maintenanceMessage: row.maintenance_message, version: row.version, lastUpdated: new Date(row.last_updated).toISOString() });
});

module.exports = router;
