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

const router = Router();

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 entityType = (req.query.entityType || "").trim();
    const entityId = (req.query.entityId || "").trim();

    const where = {};
    if (entityType) where.entityType = entityType;
    if (entityId) where.entityId = entityId;

    const [total, rows] = await Promise.all([
      prisma.activityLog.count({ where }),
      prisma.activityLog.findMany({
        where,
        orderBy: { createdAt: "desc" },
        skip,
        take: limit,
        include: {
          user: { select: { id: true, fullName: true, email: true } },
        },
      }),
    ]);

    return res.json({
      data: rows,
      pagination: { page, limit, total, totalPages: Math.ceil(total / limit) },
    });
  } catch (err) {
    return next(err);
  }
});

module.exports = router;
