import { NextResponse } from 'next/server';

import { withAuth, withPermission } from '@/lib/api/helpers';
import { parseBody } from '@/lib/api/route-helpers';
import { errorResponse } from '@/lib/errors';
import { createFromWizard } from '@/lib/services/documents.service';
import { createDocumentWizardSchema } from '@/lib/validators/documents';

export const POST = withAuth(
  withPermission('documents', 'create', async (req, ctx) => {
    try {
      const body = await parseBody(req, createDocumentWizardSchema);
      const doc = await createFromWizard(ctx.portId, body, {
        userId: ctx.userId,
        portId: ctx.portId,
        ipAddress: ctx.ipAddress,
        userAgent: ctx.userAgent,
      });
      return NextResponse.json({ data: doc }, { status: 201 });
    } catch (error) {
      return errorResponse(error);
    }
  }),
);
