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 { recordPayment } from '@/lib/services/invoices';
import { recordPaymentSchema } from '@/lib/validators/invoices';

export const PATCH = withAuth(
  withPermission('invoices', 'edit', async (req, ctx, params) => {
    try {
      const body = await parseBody(req, recordPaymentSchema);
      const invoice = await recordPayment(params.id!, ctx.portId, body, {
        userId: ctx.userId,
        portId: ctx.portId,
        ipAddress: ctx.ipAddress,
        userAgent: ctx.userAgent,
      });
      return NextResponse.json({ data: invoice });
    } catch (error) {
      return errorResponse(error);
    }
  }),
);
