import { Router } from "express";
import { z } from "zod";

import { prisma } from "../db";
import { requireAuth, type AuthRequest } from "../middleware/auth";

export const inviteRouter = Router();

inviteRouter.use(requireAuth);

const createSchema = z.object({
  maxUses: z.number().int().min(1).max(20).optional(),
  expiresInDays: z.number().int().min(1).max(30).optional(),
});

inviteRouter.post("/", async (req: AuthRequest, res) => {
  const parsed = createSchema.safeParse(req.body ?? {});
  if (!parsed.success) {
    return res.status(400).json({ error: "Invalid payload" });
  }

  const maxUses = parsed.data.maxUses ?? 5;
  const expiresInDays = parsed.data.expiresInDays ?? 7;
  const expiresAt = new Date(Date.now() + expiresInDays * 24 * 60 * 60 * 1000);
  const code = `INV-${Math.random().toString(36).slice(2, 8).toUpperCase()}`;

  const invite = await prisma.invite.create({
    data: {
      code,
      creatorId: req.userId!,
      maxUses,
      expiresAt,
    },
  });
  return res.json(invite);
});

inviteRouter.get("/", async (req: AuthRequest, res) => {
  const invites = await prisma.invite.findMany({
    where: { creatorId: req.userId! },
    orderBy: { createdAt: "desc" },
  });
  return res.json(invites);
});

inviteRouter.post("/:id/revoke", async (req: AuthRequest, res) => {
  const invite = await prisma.invite.updateMany({
    where: { id: req.params.id, creatorId: req.userId! },
    data: { revokedAt: new Date() },
  });
  if (invite.count === 0) {
    return res.status(404).json({ error: "Invite not found" });
  }
  return res.json({ ok: true });
});
