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

import { withAuth, withPermission } from '@/lib/api/helpers';
import { parseBody } from '@/lib/api/route-helpers';
import { errorResponse } from '@/lib/errors';
import { WEBHOOK_EVENTS } from '@/lib/services/webhook-event-map';
import { sendTestWebhook } from '@/lib/services/webhooks.service';

const testWebhookSchema = z.object({
  eventType: z.enum(WEBHOOK_EVENTS).default('client.created'),
});

// ─── POST /api/v1/admin/webhooks/[webhookId]/test ─────────────────────────────

export const POST = withAuth(
  withPermission('admin', 'manage_webhooks', async (req: NextRequest, ctx, params) => {
    try {
      const { webhookId } = params;
      const body = await parseBody(req, testWebhookSchema);
      const result = await sendTestWebhook(ctx.portId, webhookId!, body.eventType);
      return NextResponse.json({ data: result });
    } catch (error) {
      return errorResponse(error);
    }
  }),
);
