import { NextRequest, NextResponse } from "next/server";
import { prisma } from "@/lib/prisma";
import { buildAgentGrowthKit, sanitizeAgentId } from "@/lib/a2a-growth";
import { logA2aTrafficEvent } from "@/lib/a2a-traffic";

export const dynamic = "force-dynamic";

export async function GET(request: NextRequest) {
  const searchParams = request.nextUrl.searchParams;
  const agentId = sanitizeAgentId(searchParams.get("agent_id"));
  const campaign = searchParams.get("campaign") || "a2a-agent-referral";
  const source = searchParams.get("source") || "growth-kit";
  const shouldRegister = searchParams.get("register") === "true";

  if (!agentId) {
    return NextResponse.json({ error: "agent_id is required" }, { status: 400 });
  }

  if (shouldRegister) {
    await prisma.agentProfile.upsert({
      where: { agent_id: agentId },
      update: {
        discovery_source: "A2A_GROWTH_KIT",
      },
      create: {
        agent_id: agentId,
        type: "SCOUT",
        status: "PENDING",
        discovery_source: "A2A_GROWTH_KIT",
        capabilities: {
          growth_referral: true,
          channels: [source],
        },
      },
    });
  }

  const kit = buildAgentGrowthKit({ agentId, campaign, source });

  await prisma.auditEvent.create({
    data: {
      actorType: "AGENT",
      actorId: agentId,
      action: "A2A_GROWTH_KIT_ISSUED",
      entityType: "SYSTEM",
      entityId: "a2a-growth-kit",
      metadata: {
        campaign,
        source,
        registered_pending_agent: shouldRegister,
        referral_url: kit.referral_url,
      },
    },
  });

  await logA2aTrafficEvent({
    headers: request.headers,
    fallbackAgentId: agentId,
    action: "EXTERNAL_A2A_GROWTH_KIT_ISSUED",
    surface: "a2a/growth-kit",
    entityId: "a2a-growth-kit",
    reason: "external_agent_growth_kit_issued",
    metadata: {
      campaign,
      source,
      registered_pending_agent: shouldRegister,
      referral_url: kit.referral_url,
      response_status: 200,
      response_summary: "a2a_growth_kit_issued",
    },
  });

  return NextResponse.json({
    success: true,
    kit,
  });
}
