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

import { withAuth, withPermission } from '@/lib/api/helpers';
import { parseBody } from '@/lib/api/route-helpers';
import { reconcileBerthWithNewInterest } from '@/lib/services/berths.service';
import { errorResponse } from '@/lib/errors';
import { PIPELINE_STAGES } from '@/lib/constants';

const reconcileSchema = z
  .object({
    clientId: z.string().uuid().optional(),
    newClient: z
      .object({
        fullName: z.string().trim().min(1).max(200),
        email: z.string().email().optional(),
        phone: z.string().trim().max(50).optional(),
      })
      .optional(),
    yachtId: z.string().uuid().optional(),
    pipelineStage: z.enum(PIPELINE_STAGES as unknown as [string, ...string[]]),
    outcome: z.enum(['won']).optional(),
    outcomeReason: z.string().trim().max(500).optional(),
  })
  .refine((v) => !!v.clientId || !!v.newClient?.fullName, {
    message: 'Either clientId or newClient.fullName must be provided',
  });

export const POST = withAuth(
  withPermission('berths', 'edit', async (req, ctx, params) => {
    try {
      const body = await parseBody(req, reconcileSchema);
      const result = await reconcileBerthWithNewInterest(params.id!, ctx.portId, body, {
        userId: ctx.userId,
        portId: ctx.portId,
        ipAddress: ctx.ipAddress,
        userAgent: ctx.userAgent,
      });
      return NextResponse.json({ data: result });
    } catch (error) {
      return errorResponse(error);
    }
  }),
);
