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

import { withAuth, withPermission } from '@/lib/api/helpers';
import { parseBody } from '@/lib/api/route-helpers';
import { errorResponse } from '@/lib/errors';
import { createWebhookSchema } from '@/lib/validators/webhooks';
import { listWebhooks, createWebhook } from '@/lib/services/webhooks.service';

// ─── GET /api/v1/admin/webhooks ───────────────────────────────────────────────

export const GET = withAuth(
  withPermission('admin', 'manage_webhooks', async (_req: NextRequest, ctx) => {
    try {
      const data = await listWebhooks(ctx.portId);
      return NextResponse.json({ data });
    } catch (error) {
      return errorResponse(error);
    }
  }),
);

// ─── POST /api/v1/admin/webhooks ──────────────────────────────────────────────

export const POST = withAuth(
  withPermission('admin', 'manage_webhooks', async (req: NextRequest, ctx) => {
    try {
      const body = await parseBody(req, createWebhookSchema);
      const webhook = await createWebhook(ctx.portId, ctx.userId, body, {
        userId: ctx.userId,
        portId: ctx.portId,
        ipAddress: ctx.ipAddress,
        userAgent: ctx.userAgent,
      });
      return NextResponse.json({ data: webhook }, { status: 201 });
    } catch (error) {
      return errorResponse(error);
    }
  }),
);
