import { NextResponse } from 'next/server';

import { withAuth, withPermission } from '@/lib/api/helpers';
import { parseQuery, parseBody } from '@/lib/api/route-helpers';
import { errorResponse } from '@/lib/errors';
import { listExpenses, createExpense } from '@/lib/services/expenses';
import { listExpensesSchema, createExpenseSchema } from '@/lib/validators/expenses';

export const GET = withAuth(
  withPermission('expenses', 'view', async (req, ctx) => {
    try {
      const query = parseQuery(req, listExpensesSchema);
      const result = await listExpenses(ctx.portId, query);

      const { page, limit } = query;
      const totalPages = Math.ceil(result.total / limit);

      return NextResponse.json({
        data: result.data,
        pagination: {
          page,
          pageSize: limit,
          total: result.total,
          totalPages,
          hasNextPage: page < totalPages,
          hasPreviousPage: page > 1,
        },
      });
    } catch (error) {
      return errorResponse(error);
    }
  }),
);

export const POST = withAuth(
  withPermission('expenses', 'create', async (req, ctx) => {
    try {
      const body = await parseBody(req, createExpenseSchema);
      const expense = await createExpense(ctx.portId, body, {
        userId: ctx.userId,
        portId: ctx.portId,
        ipAddress: ctx.ipAddress,
        userAgent: ctx.userAgent,
      });
      return NextResponse.json({ data: expense }, { status: 201 });
    } catch (error) {
      return errorResponse(error);
    }
  }),
);
