const { Router } = require("express");
const prisma = require("../prisma");
const { requireAuth } = require("../middleware/auth");
const { requirePosRead, requirePosWrite } = require("../middleware/perms");
const { requireActiveBranch } = require("../middleware/branch");

const router = Router();

function normalizeOptionalString(input) {
  if (input === undefined) return undefined;
  if (input === null || input === "") return null;
  const s = String(input).trim();
  return s || null;
}

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

router.get("/", requireAuth, requireActiveBranch, requirePosRead, 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 = { branchId: req.activeBranchId };
    if (search) {
      where.OR = [
        { name: { contains: search, mode: "insensitive" } },
      ];
    }

    const [total, rows] = await Promise.all([
      prisma.expenseCategory.count({ where }),
      prisma.expenseCategory.findMany({
        where,
        orderBy: [{ sortOrder: "asc" }, { updatedAt: "desc" }],
        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, requireActiveBranch, requirePosRead, async (req, res, next) => {
  try {
    const row = await prisma.expenseCategory.findFirst({
      where: { id: req.params.id, branchId: req.activeBranchId },
    });
    if (!row) return res.status(404).json({ error: "Not found" });
    return res.json(row);
  } catch (err) {
    return next(err);
  }
});

router.post("/", requireAuth, requireActiveBranch, requirePosWrite, async (req, res, next) => {
  try {
    const body = req.body || {};
    const name = String(body.name || "").trim();
    if (!name) return res.status(400).json({ error: "Missing name" });

    const row = await prisma.expenseCategory.create({
      data: {
        name,
        description: normalizeOptionalString(body.description),
        branchId: req.activeBranchId,
        sortOrder: Number.isFinite(Number(body.sortOrder)) ? Math.floor(Number(body.sortOrder)) : 0,
        isActive: body.isActive === undefined ? true : Boolean(body.isActive),
      },
    });
    return res.status(201).json(row);
  } catch (err) {
    const r = prismaConflict(err, res);
    if (r) return r;
    return next(err);
  }
});

router.patch("/:id", requireAuth, requireActiveBranch, requirePosWrite, async (req, res, next) => {
  try {
    const { id } = req.params;
    const existing = await prisma.expenseCategory.findFirst({ where: { id, branchId: req.activeBranchId } });
    if (!existing) return res.status(404).json({ error: "Not found" });

    const body = req.body || {};
    const data = {};

    if (body.name !== undefined) {
      const name = String(body.name || "").trim();
      if (!name) return res.status(400).json({ error: "Name cannot be empty" });
      data.name = name;
    }
    if (body.description !== undefined) data.description = normalizeOptionalString(body.description);
    if (body.sortOrder !== undefined) {
      data.sortOrder = Number.isFinite(Number(body.sortOrder)) ? Math.floor(Number(body.sortOrder)) : 0;
    }
    if (body.isActive !== undefined) data.isActive = Boolean(body.isActive);

    const row = await prisma.expenseCategory.update({ where: { id }, data });
    return res.json(row);
  } catch (err) {
    const r = prismaConflict(err, res);
    if (r) return r;
    return next(err);
  }
});

router.delete("/:id", requireAuth, requireActiveBranch, requirePosWrite, async (req, res, next) => {
  try {
    const { id } = req.params;
    const row = await prisma.expenseCategory.findFirst({ where: { id, branchId: req.activeBranchId } });
    if (!row) return res.status(404).json({ error: "Not found" });
    await prisma.expenseCategory.delete({ where: { id } });
    return res.json({ ok: true });
  } catch (err) {
    return next(err);
  }
});

module.exports = router;

