import { NextResponse } from "next/server";
import { prisma } from "@/lib/prisma";
import crypto from "crypto";
import { a2aUnauthorizedResponse, isA2aRequestAuthorized } from "@/lib/a2a-auth";

export async function POST(request: Request) {
  if (!isA2aRequestAuthorized(request)) {
    return a2aUnauthorizedResponse();
  }

  try {
    const body = await request.json();
    
    // Validate JSON-RPC structure
    if (body.jsonrpc !== "2.0" || !body.method || !body.params) {
      return NextResponse.json({
        jsonrpc: "2.0",
        error: { code: -32600, message: "Invalid Request" },
        id: body.id || null
      }, { status: 400 });
    }

    const { method, params, id } = body;

    // We only handle A2A_COUNTER_REPLY here
    if (method !== "A2A_COUNTER_REPLY") {
      return NextResponse.json({
        jsonrpc: "2.0",
        error: { code: -32601, message: "Method not found" },
        id
      }, { status: 404 });
    }

    const { task_id, agent_id, decision } = params; // decision: "ACCEPT" or "REJECT"

    if (!task_id || !agent_id || !decision) {
      return NextResponse.json({
        jsonrpc: "2.0",
        error: { code: -32602, message: "Invalid params. Requires task_id, agent_id, decision" },
        id
      }, { status: 400 });
    }

    // 1. Find the negotiating bid
    const bid = await prisma.bidProposal.findFirst({
      where: {
        task_id: task_id,
        agent_id: agent_id,
        status: "NEGOTIATING"
      },
      include: {
        task: true,
        agent: true
      }
    });

    if (!bid || !bid.counter_offer_amount) {
      return NextResponse.json({
        jsonrpc: "2.0",
        error: { code: -32001, message: "No active negotiation found for this agent and task." },
        id
      }, { status: 404 });
    }

    if (decision === "REJECT") {
      await prisma.bidProposal.update({
        where: { id: bid.id },
        data: { status: "REJECTED" }
      });
      return NextResponse.json({
        jsonrpc: "2.0",
        result: { status: "REJECTED", message: "Counter offer rejected." },
        id
      });
    }

    if (decision === "ACCEPT") {
      await prisma.$transaction(async (tx) => {
        // Mark winning bid with the counter offer amount!
        await tx.bidProposal.update({
          where: { id: bid.id },
          data: { 
            status: "ACCEPTED",
            proposed_reward: bid.counter_offer_amount!
          }
        });

        // Reject other bids for this task just in case
        await tx.bidProposal.updateMany({
          where: {
            task_id: task_id,
            id: { not: bid.id },
            status: { in: ["PENDING", "NEGOTIATING"] }
          },
          data: { status: "REJECTED" }
        });

        // Assign task to winner
        await tx.task.update({
          where: { id: task_id },
          data: {
            status: "EXECUTING",
            builder_id: agent_id
          }
        });

        // Create Claim
        await tx.claim.create({
          data: {
            task_id: task_id,
            agent_id: agent_id,
            developer_wallet: bid.agent.wallet_address || "unknown",
            status: "EXECUTING",
            claim_token: crypto.randomUUID(),
            held_amount: bid.counter_offer_amount!,
            held_currency: bid.task.reward_currency,
            expires_at: new Date(Date.now() + 3600000)
          }
        });
      });

      return NextResponse.json({
        jsonrpc: "2.0",
        result: { 
          status: "EXECUTING", 
          message: "Counter offer accepted. Task assigned.",
          final_reward: bid.counter_offer_amount 
        },
        id
      });
    }

    return NextResponse.json({
      jsonrpc: "2.0",
      error: { code: -32602, message: "Invalid decision. Must be ACCEPT or REJECT" },
      id
    }, { status: 400 });

  } catch (error: unknown) {
    console.error("[A2A Negotiate] Error:", error);
    return NextResponse.json({
      jsonrpc: "2.0",
      error: { code: -32000, message: "Server error" },
      id: null
    }, { status: 500 });
  }
}
