import { NextResponse } from 'next/server';

import { withAuth, withPermission } from '@/lib/api/helpers';
import { errorResponse } from '@/lib/errors';
import { sendForSigning } from '@/lib/services/documents.service';

export const POST = withAuth(
  // Use the dedicated `send_for_signing` permission rather than `create`,
  // so a role with documents.create-only does not also gain the ability
  // to dispatch a Documenso send (auditor-A3 §3).
  withPermission('documents', 'send_for_signing', async (req, ctx, params) => {
    try {
      const doc = await sendForSigning(params.id!, ctx.portId, {
        userId: ctx.userId,
        portId: ctx.portId,
        ipAddress: ctx.ipAddress,
        userAgent: ctx.userAgent,
      });
      return NextResponse.json({ data: doc });
    } catch (error) {
      return errorResponse(error);
    }
  }),
);
