const router = require("express").Router();
const auth = require("../middleware/auth");
const optionalAuth = require("../middleware/optional-auth");
const { createRateLimit } = require("../middleware/rate-limit");
const controller = require("../controllers/group-invites.controller");

const inviteSummaryIpRateLimit = createRateLimit({
  keyPrefix: "invite:summary:ip",
  windowMs: 15 * 60 * 1000,
  max: 120,
  message: "Too many invite link summary requests. Please try again later.",
});

const inviteAcceptIpRateLimit = createRateLimit({
  keyPrefix: "invite:accept:ip",
  windowMs: 15 * 60 * 1000,
  max: 60,
  message: "Too many invite acceptance attempts. Please try again later.",
});

const inviteWriteUserRateLimit = createRateLimit({
  keyPrefix: "invite:write:user",
  windowMs: 15 * 60 * 1000,
  max: 60,
  message: "Too many write operations. Please try again later.",
  keyFn: (req) => (req.user?.id ? `user:${req.user.id}` : "anon"),
});

router.get("/groups/invites", auth, controller.listInviteLinks);
router.post("/groups/invites", auth, inviteWriteUserRateLimit, controller.createInviteLink);
router.post(
  "/groups/invites/revoke",
  auth,
  inviteWriteUserRateLimit,
  controller.revokeInviteLink
);
router.post(
  "/groups/invites/revive",
  auth,
  inviteWriteUserRateLimit,
  controller.reviveInviteLink
);
router.post(
  "/groups/invites/delete",
  auth,
  inviteWriteUserRateLimit,
  controller.deleteInviteLink
);

router.get("/groups/join-policy", auth, controller.getJoinPolicy);
router.post(
  "/groups/join-policy",
  auth,
  inviteWriteUserRateLimit,
  controller.setJoinPolicy
);

router.get(
  "/invite-links/:token",
  inviteSummaryIpRateLimit,
  optionalAuth,
  controller.getInviteLinkSummary
);
router.post(
  "/invite-links/:token",
  auth,
  inviteAcceptIpRateLimit,
  inviteWriteUserRateLimit,
  controller.acceptInviteLink
);

module.exports = router;
