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 { createPaymentSchema } from '@/lib/validators/payments';
import {
  createPayment,
  getDepositTotalForInterest,
  listPaymentsForInterest,
} from '@/lib/services/payments.service';

export const GET = withAuth(
  withPermission('interests', 'view', async (_req, ctx, params) => {
    try {
      const interestId = params.id!;
      const [payments, depositTotal] = await Promise.all([
        listPaymentsForInterest(interestId, ctx.portId),
        getDepositTotalForInterest(interestId, ctx.portId),
      ]);
      return NextResponse.json({ data: { payments, depositTotal } });
    } catch (error) {
      return errorResponse(error);
    }
  }),
);

export const POST = withAuth(
  withPermission('payments', 'record', async (req, ctx, params) => {
    try {
      // Body's interestId must match the URL param - defense-in-depth against
      // a client that sends one ID in the URL but another in the body.
      const body = await parseBody(req, createPaymentSchema);
      if (body.interestId !== params.id) {
        throw new ValidationError('interestId in body must match URL parameter');
      }
      const payment = await createPayment(ctx.portId, body, {
        userId: ctx.userId,
        portId: ctx.portId,
        ipAddress: ctx.ipAddress,
        userAgent: ctx.userAgent,
      });
      return NextResponse.json({ data: payment }, { status: 201 });
    } catch (error) {
      return errorResponse(error);
    }
  }),
);
