import { NextResponse } from 'next/server';
import { z } from 'zod';

import { type RouteHandler } from '@/lib/api/helpers';
import { parseBody } from '@/lib/api/route-helpers';
import { errorResponse } from '@/lib/errors';
import { applyParseResults, type ExtractedBerthFields } from '@/lib/services/berth-pdf.service';

const postBodySchema = z.object({
  versionId: z.string().min(1),
  fieldsToApply: z.record(z.string(), z.unknown()),
});

export const postHandler: RouteHandler = async (req, ctx, params) => {
  try {
    const body = await parseBody(req, postBodySchema);
    const result = await applyParseResults(
      params.id!,
      body.versionId,
      body.fieldsToApply as Partial<ExtractedBerthFields>,
      ctx.portId,
    );
    return NextResponse.json({ data: result });
  } catch (error) {
    return errorResponse(error);
  }
};
