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 { getExpenseById, updateExpense, archiveExpense } from '@/lib/services/expenses';
import { updateExpenseSchema } from '@/lib/validators/expenses';

export const GET = withAuth(
  withPermission('expenses', 'view', async (_req, ctx, params) => {
    try {
      const expense = await getExpenseById(params.id!, ctx.portId);
      return NextResponse.json({ data: expense });
    } catch (error) {
      return errorResponse(error);
    }
  }),
);

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

export const DELETE = withAuth(
  withPermission('expenses', 'delete', async (_req, ctx, params) => {
    try {
      await archiveExpense(params.id!, ctx.portId, {
        userId: ctx.userId,
        portId: ctx.portId,
        ipAddress: ctx.ipAddress,
        userAgent: ctx.userAgent,
      });
      return new NextResponse(null, { status: 204 });
    } catch (error) {
      return errorResponse(error);
    }
  }),
);
