import { NextResponse } from 'next/server';

import { withAuth, withPermission } from '@/lib/api/helpers';
import { errorResponse } from '@/lib/errors';
import {
  enableSigningAutomation,
  disableSigningAutomation,
} from '@/lib/services/signing-automation.service';

/**
 * POST `/api/v1/documents/[id]/automate`
 *
 * Enable Automate Signing on the document. The service resolves the
 * mode (sequential_auto vs concurrent_auto) from the envelope's
 * signing order and fires the appropriate invitation set. Returns
 * the chosen mode + how many invitations were dispatched.
 *
 * DELETE on the same path reverts to manual mode.
 *
 * Permission: documents.send_for_signing — same as the per-signer
 * Send invitation route since the side effects are equivalent.
 */
export const POST = withAuth(
  withPermission('documents', 'send_for_signing', async (req, ctx, params) => {
    try {
      const documentId = params.id!;
      const result = await enableSigningAutomation(documentId, ctx.portId, {
        userId: ctx.userId,
        portId: ctx.portId,
        ipAddress: req.headers.get('x-forwarded-for') ?? '0.0.0.0',
        userAgent: req.headers.get('user-agent') ?? '',
      });
      return NextResponse.json({ data: result });
    } catch (error) {
      return errorResponse(error);
    }
  }),
);

export const DELETE = withAuth(
  withPermission('documents', 'send_for_signing', async (req, ctx, params) => {
    try {
      const documentId = params.id!;
      await disableSigningAutomation(documentId, ctx.portId, {
        userId: ctx.userId,
        portId: ctx.portId,
        ipAddress: req.headers.get('x-forwarded-for') ?? '0.0.0.0',
        userAgent: req.headers.get('user-agent') ?? '',
      });
      return new NextResponse(null, { status: 204 });
    } catch (error) {
      return errorResponse(error);
    }
  }),
);
