import { NextRequest, NextResponse } from "next/server";
import { db, adminWebhooks, adminWebhookDeliveries, eq, desc } from "@epicure/db";
import { requireAdmin } from "@/lib/api-auth";

type Params = { params: Promise<{ id: string }> };

export async function GET(_req: NextRequest, { params }: Params) {
  const { response } = await requireAdmin();
  if (response) return response;

  const { id } = await params;

  const hook = await db.query.adminWebhooks.findFirst({ where: eq(adminWebhooks.id, id), columns: { id: true } });
  if (!hook) return NextResponse.json({ error: "Not found" }, { status: 404 });

  const deliveries = await db
    .select()
    .from(adminWebhookDeliveries)
    .where(eq(adminWebhookDeliveries.webhookId, id))
    .orderBy(desc(adminWebhookDeliveries.createdAt))
    .limit(20);

  return NextResponse.json(deliveries);
}
