import { Router, Request, Response } from 'express';
import { authenticate, requireRole } from '../../middleware/auth';
import { AuditAction } from '@prisma/client';
import { prisma } from '../../lib/prisma';
import { createInviteCode, listInviteCodes, revokeInviteCode } from '../../services/invite-code.service';

const router = Router();

/**
 * POST /api/invite-codes
 * Generate a new invite code for agent registration.
 */
router.post('/', authenticate, requireRole('SUPER_ADMIN', 'OPERATOR'), async (req: Request, res: Response) => {
  const userId = (req as unknown as { user: { id: string } }).user.id;
  const { expiryHours } = req.body || {};

  const invite = await createInviteCode(userId, expiryHours);

  await prisma.auditLog.create({
    data: {
      userId,
      action: AuditAction.INVITE_CREATE,
      details: { code: invite.code, expiresAt: invite.expiresAt.toISOString() },
      ipAddress: req.ip || null,
    },
  });

  res.status(201).json(invite);
});

/**
 * GET /api/invite-codes
 * List all invite codes.
 */
router.get('/', authenticate, requireRole('SUPER_ADMIN', 'OPERATOR'), async (req: Request, res: Response) => {
  const page = Number(req.query.page) || 1;
  const limit = Number(req.query.limit) || 50;
  const result = await listInviteCodes(page, limit);
  res.json(result);
});

/**
 * DELETE /api/invite-codes/:id
 * Revoke an unused invite code.
 */
router.delete('/:id', authenticate, requireRole('SUPER_ADMIN', 'OPERATOR'), async (req: Request, res: Response) => {
  const userId = (req as unknown as { user: { id: string } }).user.id;
  await revokeInviteCode(req.params.id as string);

  await prisma.auditLog.create({
    data: {
      userId,
      action: AuditAction.INVITE_REVOKE,
      details: { inviteCodeId: req.params.id },
      ipAddress: req.ip || null,
    },
  });

  res.json({ message: 'Invite code revoked' });
});

export default router;
