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 { updateWebhookSchema } from '@/lib/validators/webhooks';
import { getWebhook, updateWebhook, deleteWebhook } from '@/lib/services/webhooks.service';

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

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

// ─── PATCH /api/v1/admin/webhooks/[webhookId] ─────────────────────────────────

export const PATCH = withAuth(
  withPermission('admin', 'manage_webhooks', async (req: NextRequest, ctx, params) => {
    try {
      const { webhookId } = params;
      const body = await parseBody(req, updateWebhookSchema);
      const data = await updateWebhook(ctx.portId, webhookId!, body, {
        userId: ctx.userId,
        portId: ctx.portId,
        ipAddress: ctx.ipAddress,
        userAgent: ctx.userAgent,
      });
      return NextResponse.json({ data });
    } catch (error) {
      return errorResponse(error);
    }
  }),
);

// ─── DELETE /api/v1/admin/webhooks/[webhookId] ────────────────────────────────

export const DELETE = withAuth(
  withPermission('admin', 'manage_webhooks', async (_req: NextRequest, ctx, params) => {
    try {
      const { webhookId } = params;
      await deleteWebhook(ctx.portId, webhookId!, {
        userId: ctx.userId,
        portId: ctx.portId,
        ipAddress: ctx.ipAddress,
        userAgent: ctx.userAgent,
      });
      return new NextResponse(null, { status: 204 });
    } catch (error) {
      return errorResponse(error);
    }
  }),
);
