import { NextResponse } from "next/server";
import { logApiError } from "@/lib/api/security";
import { createRouteClient } from "@/lib/supabase/route";
import { sql } from "@/lib/db/postgres";
import { canManageWorkspace } from "@/lib/developers/auth";

export async function GET(
  req: Request,
  context: { params: Promise<{ id: string }> }
) {
  try {
    const supabase = await createRouteClient();
    const {
      data: { user },
    } = await supabase.auth.getUser();

    if (!user) {
      return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
    }

    const { id } = await context.params;
    const url = new URL(req.url);
    const limit = Math.min(Math.max(Number(url.searchParams.get("limit") || 20), 1), 50);

    const { rows: endpointRows } = await sql`
      SELECT id, team_id FROM webhook_endpoints WHERE id = ${id}
    `;
    const endpoint = endpointRows[0];

    if (!endpoint) {
      return NextResponse.json({ error: "Webhook not found" }, { status: 404 });
    }

    const manageable = await canManageWorkspace(user.id, (endpoint.team_id as string | null) || null);
    if (!manageable) {
      return NextResponse.json({ error: "Forbidden" }, { status: 403 });
    }

    const { rows } = await sql`
      SELECT id, endpoint_id, user_id, team_id, event_type, delivery_id, payload, response_status, response_body, success, created_at
      FROM webhook_deliveries
      WHERE endpoint_id = ${id}
      ORDER BY created_at DESC
      LIMIT ${limit}
    `;

    return NextResponse.json({ deliveries: rows });
  } catch (error) {
    logApiError("Webhook deliveries GET error", error);
    return NextResponse.json({ error: "Failed to load deliveries" }, { status: 500 });
  }
}
