import { NextResponse } from 'next/server';

import { withAuth, withPermission } from '@/lib/api/helpers';
import { parseBody } from '@/lib/api/route-helpers';
import { errorResponse, ValidationError } from '@/lib/errors';
import { convertInquiryToClient, convertInquiryToInterest } from '@/lib/services/inquiries.service';
import { convertInquirySchema } from '@/lib/validators/inquiries';

export const POST = withAuth(
  withPermission('inquiries', 'manage', async (req, ctx, params) => {
    try {
      const id = params.id;
      if (!id) throw new ValidationError('id is required');
      const { target } = await parseBody(req, convertInquirySchema);
      const meta = {
        userId: ctx.userId,
        portId: ctx.portId,
        ipAddress: ctx.ipAddress,
        userAgent: ctx.userAgent,
      };
      const data =
        target === 'interest'
          ? await convertInquiryToInterest(id, ctx.portId, meta)
          : await convertInquiryToClient(id, ctx.portId, meta);
      return NextResponse.json({ data });
    } catch (error) {
      return errorResponse(error);
    }
  }),
);
