import { NextRequest, NextResponse } from 'next/server';

import { withAuth, withPermission } from '@/lib/api/helpers';
import { parseQuery } from '@/lib/api/route-helpers';
import { errorResponse } from '@/lib/errors';
import { listDeliveriesSchema } from '@/lib/validators/webhooks';
import { listDeliveries } from '@/lib/services/webhooks.service';

// ─── GET /api/v1/admin/webhooks/[webhookId]/deliveries ────────────────────────

export const GET = withAuth(
  withPermission('admin', 'manage_webhooks', async (req: NextRequest, ctx, params) => {
    try {
      const { webhookId } = params;
      const query = parseQuery(req, listDeliveriesSchema);
      const result = await listDeliveries(ctx.portId, webhookId!, query);
      return NextResponse.json(result);
    } catch (error) {
      return errorResponse(error);
    }
  }),
);
