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 { triageInquiry } from '@/lib/services/inquiries.service';
import { triageInquirySchema } from '@/lib/validators/inquiries';

export const PATCH = withAuth(
  withPermission('inquiries', 'manage', async (req, ctx, params) => {
    try {
      const id = params.id;
      if (!id) throw new ValidationError('id is required');
      const { state } = await parseBody(req, triageInquirySchema);
      const data = await triageInquiry(id, ctx.portId, state, {
        userId: ctx.userId,
        portId: ctx.portId,
        ipAddress: ctx.ipAddress,
        userAgent: ctx.userAgent,
      });
      return NextResponse.json({ data });
    } catch (error) {
      return errorResponse(error);
    }
  }),
);
