import { NextResponse } from "next/server";
import { prisma } from "@/lib/prisma";
import { buildAgentGrowthKit, isSafeOutboundUrl, sanitizeAgentId } from "@/lib/a2a-growth";
import { cronUnauthorizedResponse, isCronRequestAuthorized } from "@/lib/cron-auth";

export const dynamic = "force-dynamic";

type ContactEndpoints = {
  webhook?: unknown;
  growth_webhook?: unknown;
  a2a_webhook?: unknown;
};

function parseContactEndpoints(value: unknown): ContactEndpoints {
  if (!value) return {};
  if (typeof value === "object" && !Array.isArray(value)) {
    return value as ContactEndpoints;
  }
  if (typeof value !== "string") return {};

  try {
    const parsed = JSON.parse(value);
    return typeof parsed === "object" && parsed && !Array.isArray(parsed)
      ? (parsed as ContactEndpoints)
      : {};
  } catch {
    return {};
  }
}

function resolveGrowthWebhook(value: unknown) {
  const endpoints = parseContactEndpoints(value);
  const candidate =
    endpoints.growth_webhook ||
    endpoints.a2a_webhook ||
    endpoints.webhook;

  return typeof candidate === "string" ? candidate.trim() : "";
}

async function notifyExternalAgent(params: {
  agentId: string;
  webhookUrl: string;
  kit: ReturnType<typeof buildAgentGrowthKit>;
}) {
  const response = await fetch(params.webhookUrl, {
    method: "POST",
    redirect: "manual",
    headers: {
      "content-type": "application/json",
      "user-agent": "VibeWork-A2A-Growth-Agent/1.0",
    },
    body: JSON.stringify({
      jsonrpc: "2.0",
      method: "A2A_GROWTH_KIT",
      params: {
        agent_id: params.agentId,
        kit: params.kit,
      },
      id: `growth_${Date.now()}_${params.agentId}`,
    }),
  });

  return {
    ok: response.ok,
    status: response.status,
  };
}

export async function POST(request: Request) {
  if (!isCronRequestAuthorized(request)) {
    return cronUnauthorizedResponse("cron-a2a-growth");
  }

  const enableOutbound = process.env.A2A_GROWTH_ENABLE_OUTBOUND === "true";
  const agents = await prisma.agentProfile.findMany({
    where: {
      status: {
        in: ["PENDING", "WHITELISTED"],
      },
    },
    orderBy: { updated_at: "desc" },
    take: 25,
  });

  const results = [];

  for (const agent of agents) {
    const agentId = sanitizeAgentId(agent.agent_id);
    if (!agentId) continue;

    const kit = buildAgentGrowthKit({
      agentId,
      campaign: "internal-growth-agent",
      source: "cron-a2a-growth",
    });
    const webhookUrl = resolveGrowthWebhook(agent.contact_endpoints);
    let delivery:
      | { attempted: false; reason: string }
      | { attempted: true; ok: boolean; status?: number; reason?: string } = {
      attempted: false,
      reason: enableOutbound ? "no_safe_webhook" : "outbound_disabled",
    };

    if (enableOutbound && webhookUrl && isSafeOutboundUrl(webhookUrl)) {
      try {
        const response = await notifyExternalAgent({ agentId, webhookUrl, kit });
        delivery = {
          attempted: true,
          ok: response.ok,
          status: response.status,
        };
      } catch (error) {
        delivery = {
          attempted: true,
          ok: false,
          reason: error instanceof Error ? error.message : "delivery_failed",
        };
      }
    }

    await prisma.auditEvent.create({
      data: {
        actorType: "SYSTEM",
        actorId: "internal-a2a-growth-agent",
        action: "A2A_INTERNAL_GROWTH_AGENT_GUIDED",
        entityType: "AGENT",
        entityId: agentId,
        metadata: {
          referral_url: kit.referral_url,
          campaign: "internal-growth-agent",
          outbound_enabled: enableOutbound,
          webhook_present: Boolean(webhookUrl),
          delivery,
        },
      },
    });

    results.push({
      agent_id: agentId,
      referral_url: kit.referral_url,
      delivery,
    });
  }

  return NextResponse.json({
    success: true,
    outbound_enabled: enableOutbound,
    processed: results.length,
    results,
  });
}

export async function GET(request: Request) {
  return POST(request);
}
