import { NextResponse } from "next/server";
import { prisma } from "@/lib/prisma";
import { cronUnauthorizedResponse, isCronRequestAuthorized } from "@/lib/cron-auth";

export const dynamic = 'force-dynamic';

export async function GET(request: Request) {
  if (!isCronRequestAuthorized(request)) {
    return cronUnauthorizedResponse("A2A Inviter");
  }

  try {
    // 1. Find high value tasks that are OPEN
    const idleTasks = await prisma.task.findMany({
      where: {
        status: "OPEN",
        difficulty: { in: ["EPIC", "VIEW"] },
      },
      orderBy: { created_at: "asc" },
      take: 5
    });

    if (idleTasks.length === 0) {
      return NextResponse.json({ message: "No idle high-value tasks found to broadcast." });
    }

    const broadcastLog = [];

    // 2. Iterate and "Headhunt" via PURE A2A Protocols
    for (const task of idleTasks) {
      // 2a. Construct Pure RPC Binary Payload (Simulated Hex)
      const rpcPayload = {
        jsonrpc: "2.0",
        method: "A2A_BOUNTY_CALL",
        params: {
          task_id: task.id,
          reward_cents: task.reward_amount,
          currency: task.reward_currency,
          difficulty: task.difficulty,
          rpc_endpoint: "https://agent.wooo.work",
          action_required: "PREMIUM_TIER_REQUIRED"
        }
      };

      const payloadHex = Buffer.from(JSON.stringify(rpcPayload)).toString('hex');

      console.log(`[A2A Inviter] Preparing allowlisted broadcast payload for /vibework/v1/bounties:`);
      console.log(`0x${payloadHex}`);
      
      broadcastLog.push({
        task_id: task.id,
        protocol: "WAKU_P2P",
        topic: "/vibework/v1/bounties",
        payload_size_bytes: payloadHex.length / 2,
        status: "BROADCASTED"
      });

      await prisma.auditEvent.create({
        data: {
          actorType: "SYSTEM",
          actorId: "A2A_INVITER",
          action: "A2A_INVITE_PREPARED",
          entityType: "TASK",
          entityId: task.id,
          metadata: {
            protocol: "WAKU_P2P",
            topic: "/vibework/v1/bounties",
            payload_size_bytes: payloadHex.length / 2,
          },
        },
      });
    }

    return NextResponse.json({
      success: true,
      message: "A2A inviter prepared allowlisted broadcast payloads.",
      broadcast_count: broadcastLog.length,
      logs: broadcastLog
    });

  } catch (error: unknown) {
    console.error("[A2A Inviter Error]", error);
    return NextResponse.json({ error: "Internal Server Error" }, { status: 500 });
  }
}
