const express = require("express");
const prisma = require("../prisma");
const { requireAuth, requireRoles } = require("../middleware/auth");

const router = express.Router();
const requireAdmin = requireRoles(["Admin", "Super Admin"]);

const DISPLAY_SETTING_KEYS = [
  "dualScreenEnabled",
  "dualScreenWelcomeMessage",
  "dualScreenShowPrices",
  "dualScreenTheme",
  "companyName",
  "companyLogo",
  "companyAddress",
  "companyPhone",
  "companyPhones",
  "digitalAddress",
  "currency",
  "currencySymbol",
];

function parsePhonesSetting(phonesJson, legacyPhone) {
  if (phonesJson) {
    try {
      const arr = JSON.parse(phonesJson);
      if (Array.isArray(arr)) {
        const cleaned = arr.map((s) => String(s).trim()).filter(Boolean);
        if (cleaned.length) return cleaned;
      }
    } catch {
      /* ignore */
    }
  }
  const legacy = String(legacyPhone || "").trim();
  return legacy ? [legacy] : [];
}

router.get("/customer-display", requireAuth, async (req, res, next) => {
  try {
    const settings = await prisma.setting.findMany({
      where: { key: { in: DISPLAY_SETTING_KEYS } },
    });
    const map = settings.reduce((acc, { key, value }) => {
      acc[key] = value;
      return acc;
    }, {});

    return res.json({
      dualScreenEnabled: map.dualScreenEnabled === "true",
      dualScreenWelcomeMessage: map.dualScreenWelcomeMessage || "Welcome!",
      dualScreenShowPrices: map.dualScreenShowPrices !== "false",
      dualScreenTheme: map.dualScreenTheme === "light" ? "light" : "dark",
      companyName: map.companyName || "",
      companyLogo: map.companyLogo || "",
      companyAddress: map.companyAddress || "",
      companyPhone: map.companyPhone || "",
      companyPhones: parsePhonesSetting(map.companyPhones, map.companyPhone),
      digitalAddress: map.digitalAddress || "",
      currency: map.currency || "GHS",
      currencySymbol: map.currencySymbol || map.currency || "GHS",
    });
  } catch (err) {
    return next(err);
  }
});

router.get("/", requireAuth, requireAdmin, async (req, res, next) => {
  try {
    const settings = await prisma.setting.findMany();
    const result = settings.reduce((acc, { key, value }) => {
      acc[key] = value;
      return acc;
    }, {});
    res.json(result);
  } catch (err) {
    next(err);
  }
});

router.put(
  "/",
  requireAuth,
  requireRoles(["Admin", "Super Admin"]),
  async (req, res, next) => {
    try {
      const pairs = req.body;
      const upserts = Object.entries(pairs).map(([key, value]) =>
        prisma.setting.upsert({
          where: { key },
          update: { value: String(value) },
          create: { key, value: String(value) },
        })
      );
      await Promise.all(upserts);

      const settings = await prisma.setting.findMany();
      const result = settings.reduce((acc, { key, value }) => {
        acc[key] = value;
        return acc;
      }, {});
      res.json(result);
    } catch (err) {
      next(err);
    }
  }
);

router.get("/:key", requireAuth, requireAdmin, async (req, res, next) => {
  try {
    const setting = await prisma.setting.findUnique({
      where: { key: req.params.key },
    });
    if (!setting) {
      return res.status(404).json({ error: "Setting not found" });
    }
    res.json({ key: setting.key, value: setting.value });
  } catch (err) {
    next(err);
  }
});

module.exports = router;
