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 { listInvoices, createInvoice } from '@/lib/services/invoices';
import { listInvoicesSchema, createInvoiceSchema } from '@/lib/validators/invoices';

export const GET = withAuth(
  withPermission('invoices', 'view', async (req, ctx) => {
    try {
      const query = parseQuery(req, listInvoicesSchema);
      const result = await listInvoices(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('invoices', 'create', async (req, ctx) => {
    try {
      const body = await parseBody(req, createInvoiceSchema);
      const invoice = await createInvoice(ctx.portId, body, {
        userId: ctx.userId,
        portId: ctx.portId,
        ipAddress: ctx.ipAddress,
        userAgent: ctx.userAgent,
      });
      return NextResponse.json({ data: invoice }, { status: 201 });
    } catch (error) {
      return errorResponse(error);
    }
  }),
);
