import { getDb } from "../config/db.js";
import { roles } from "../utils/constants.js";

export const getSettings = async (req, res) => {
  const db = getDb();
  
  // 1. Fetch Global System Settings if Super Admin
  let system = {};
  if (req.user.role === roles.SUPER_ADMIN) {
    const [rows] = await db.execute("SELECT setting_key, setting_value FROM system_settings");
    rows.forEach(row => system[row.setting_key] = row.setting_value);
  }

  // 2. Base settings object
  const settings = {
    systemName: "North East State E-Notary",
    version: "1.0.0",
    maintenance: false,
    office: req.user.notary_id ? {
      name: req.user.notary_name,
      region: req.user.region,
      district: req.user.district
    } : null,
    systemConfig: system // Only populated for super admins
  };
  
  res.json(settings);
};

export const updateSystemSettings = async (req, res) => {
  if (req.user.role !== roles.SUPER_ADMIN) {
    return res.status(403).json({ message: "Oggolaansho looma hayo" });
  }

  const db = getDb();
  const config = req.body; // { sms_gateway_url: '...', ... }

  for (const [key, value] of Object.entries(config)) {
    await db.execute(
      "UPDATE system_settings SET setting_value = ? WHERE setting_key = ?",
      [String(value), key]
    );
  }

  res.json({ message: "System settings updated successfully." });
};
