import { NextResponse } from 'next/server';

import { requireSuperAdmin, withAuth, withPermission } from '@/lib/api/helpers';
import { errorResponse } from '@/lib/errors';
import { resendCrmInvite } from '@/lib/services/crm-invite.service';

// Resend mints a fresh token + new email on a global invite row;
// restrict to super-admins to match revoke/list and avoid cross-tenant
// re-issuance of foreign-port invitations.
export const POST = withAuth(
  withPermission('admin', 'manage_users', async (_req, ctx, params) => {
    try {
      requireSuperAdmin(ctx, 'admin.invitations.resend');
      const id = params.id ?? '';
      const result = await resendCrmInvite(id, {
        userId: ctx.userId,
        portId: ctx.portId,
        ipAddress: ctx.ipAddress,
        userAgent: ctx.userAgent,
      });
      return NextResponse.json({ data: result });
    } catch (error) {
      return errorResponse(error);
    }
  }),
);
