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

const router = Router();

function prismaConflict(err, res) {
  if (err.code === "P2002") {
    return res.status(409).json({ error: "Template name already exists" });
  }
  return null;
}

router.get("/", requireAuth, requireRoles(["Admin", "Super Admin"]), async (req, res, next) => {
  try {
    const page = Math.max(1, parseInt(req.query.page) || 1);
    const limit = Math.min(100, Math.max(1, parseInt(req.query.limit) || 25));
    const skip = (page - 1) * limit;
    const search = (req.query.search || "").trim();
    const where = search ? { name: { contains: search, mode: "insensitive" } } : {};
    const [total, rows] = await Promise.all([
      prisma.smsTemplate.count({ where }),
      prisma.smsTemplate.findMany({ where, orderBy: { name: "asc" }, skip, take: limit }),
    ]);
    return res.json({
      data: rows,
      pagination: { page, limit, total, totalPages: Math.ceil(total / limit) },
    });
  } catch (err) {
    return next(err);
  }
});

router.get("/:id", requireAuth, requireRoles(["Admin", "Super Admin"]), async (req, res, next) => {
  try {
    const row = await prisma.smsTemplate.findUnique({ where: { id: req.params.id } });
    if (!row) return res.status(404).json({ error: "Not found" });
    return res.json(row);
  } catch (err) {
    return next(err);
  }
});

router.post("/", requireAuth, requireRoles(["Admin", "Super Admin"]), async (req, res, next) => {
  try {
    const { name, body, variables, isActive } = req.body || {};
    if (!name?.trim() || !body?.trim()) {
      return res.status(400).json({ error: "Name and body are required" });
    }
    const row = await prisma.smsTemplate.create({
      data: {
        name: String(name).trim(),
        body: String(body),
        variables: Array.isArray(variables) ? variables : undefined,
        isActive: typeof isActive === "boolean" ? isActive : true,
      },
    });
    auditFromReq(req, { action: "create", entityType: "SmsTemplate", entityId: row.id, summary: row.name });
    return res.status(201).json(row);
  } catch (err) {
    const r = prismaConflict(err, res);
    if (r) return r;
    return next(err);
  }
});

router.patch("/:id", requireAuth, requireRoles(["Admin", "Super Admin"]), async (req, res, next) => {
  try {
    const existing = await prisma.smsTemplate.findUnique({ where: { id: req.params.id } });
    if (!existing) return res.status(404).json({ error: "Not found" });
    const { name, body, variables, isActive } = req.body || {};
    const data = {};
    if (name !== undefined) data.name = String(name).trim();
    if (body !== undefined) data.body = String(body);
    if (variables !== undefined) data.variables = Array.isArray(variables) ? variables : null;
    if (isActive !== undefined) data.isActive = Boolean(isActive);
    const row = await prisma.smsTemplate.update({ where: { id: req.params.id }, data });
    auditFromReq(req, { action: "update", entityType: "SmsTemplate", entityId: row.id, summary: row.name });
    return res.json(row);
  } catch (err) {
    const r = prismaConflict(err, res);
    if (r) return r;
    return next(err);
  }
});

router.delete("/:id", requireAuth, requireRoles(["Admin", "Super Admin"]), async (req, res, next) => {
  try {
    const row = await prisma.smsTemplate.findUnique({ where: { id: req.params.id } });
    if (!row) return res.status(404).json({ error: "Not found" });
    await prisma.smsTemplate.delete({ where: { id: req.params.id } });
    auditFromReq(req, { action: "delete", entityType: "SmsTemplate", entityId: row.id, summary: row.name });
    return res.json({ ok: true });
  } catch (err) {
    return next(err);
  }
});

module.exports = router;
