import { NextRequest, NextResponse } from "next/server";
import { z } from "zod";
import { db, adminWebhooks, eq } from "@epicure/db";
import { requireAdmin } from "@/lib/api-auth";
import { validateWebhookUrl } from "@/lib/validate-webhook-url";
import { ADMIN_WEBHOOK_EVENTS } from "@/lib/admin-webhooks";

const UpdateWebhookBody = z.object({
  url: z.string().min(1).max(2048).optional(),
  events: z.array(z.enum(ADMIN_WEBHOOK_EVENTS)).optional(),
  active: z.boolean().optional(),
});

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

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

  const { id } = await params;

  const existing = await db.select({ id: adminWebhooks.id }).from(adminWebhooks).where(eq(adminWebhooks.id, id)).limit(1);
  if (existing.length === 0) return NextResponse.json({ error: "Not found" }, { status: 404 });

  await db.delete(adminWebhooks).where(eq(adminWebhooks.id, id));
  return new NextResponse(null, { status: 204 });
}

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

  const { id } = await params;

  const existing = await db.select({ id: adminWebhooks.id }).from(adminWebhooks).where(eq(adminWebhooks.id, id)).limit(1);
  if (existing.length === 0) return NextResponse.json({ error: "Not found" }, { status: 404 });

  const body = await req.json() as unknown;
  const parsed = UpdateWebhookBody.safeParse(body);
  if (!parsed.success) {
    return NextResponse.json({ error: "Validation error", issues: parsed.error.issues }, { status: 400 });
  }

  if (parsed.data.url) {
    const ssrfError = await validateWebhookUrl(parsed.data.url);
    if (ssrfError) return NextResponse.json({ error: ssrfError }, { status: 400 });
  }

  const updates: Partial<{ url: string; events: string[]; active: boolean }> = {};
  if (parsed.data.url !== undefined) updates.url = parsed.data.url;
  if (parsed.data.events !== undefined) updates.events = parsed.data.events;
  if (parsed.data.active !== undefined) updates.active = parsed.data.active;

  if (Object.keys(updates).length === 0) {
    return NextResponse.json({ error: "No fields to update" }, { status: 400 });
  }

  await db.update(adminWebhooks).set(updates).where(eq(adminWebhooks.id, id));

  const updated = await db
    .select({
      id: adminWebhooks.id,
      url: adminWebhooks.url,
      events: adminWebhooks.events,
      active: adminWebhooks.active,
      createdAt: adminWebhooks.createdAt,
    })
    .from(adminWebhooks)
    .where(eq(adminWebhooks.id, id))
    .limit(1);

  return NextResponse.json(updated[0]);
}
