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

const router = Router();
router.use(requireAuth, requireActiveBranch);

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

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

    const [total, rows] = await Promise.all([
      prisma.tax.count({ where }),
      prisma.tax.findMany({
        where,
        orderBy: [{ sortOrder: "asc" }, { 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", requireInventoryRead, async (req, res, next) => {
  try {
    const row = await prisma.tax.findFirst({ where: branchWhere(req, { 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("/", requireInventoryWrite, async (req, res, next) => {
  try {
    const { name, rate, sortOrder, isActive } = req.body || {};
    if (!name || !String(name).trim()) return res.status(400).json({ error: "Missing name" });

    const r = Number(rate);
    const row = await prisma.tax.create({
      data: {
        name: String(name).trim(),
        rate: Number.isFinite(r) ? r : 0,
        sortOrder: Number.isFinite(Number(sortOrder)) ? Number(sortOrder) : 0,
        isActive: typeof isActive === "boolean" ? isActive : true,
        branchId: req.activeBranchId,
      },
    });
    return res.status(201).json(row);
  } catch (err) {
    const r = prismaConflict(err, res);
    if (r) return r;
    return next(err);
  }
});

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

    const { name, rate, sortOrder, isActive } = req.body || {};
    if (name !== undefined && !String(name).trim()) {
      return res.status(400).json({ error: "Name cannot be empty" });
    }

    const data = {};
    if (name !== undefined) data.name = String(name).trim();
    if (rate !== undefined) {
      const r = Number(rate);
      data.rate = Number.isFinite(r) ? r : 0;
    }
    if (sortOrder !== undefined) data.sortOrder = Number.isFinite(Number(sortOrder)) ? Number(sortOrder) : 0;
    if (isActive !== undefined) data.isActive = Boolean(isActive);

    const row = await prisma.tax.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", requireInventoryWrite, async (req, res, next) => {
  try {
    const { id } = req.params;
    const row = await prisma.tax.findFirst({ where: branchWhere(req, { id }) });
    if (!row) return res.status(404).json({ error: "Not found" });
    await prisma.tax.delete({ where: { id } });
    return res.json({ ok: true });
  } catch (err) {
    return next(err);
  }
});

module.exports = router;

