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

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

  try {
    const body = await request.json();

    if (body.jsonrpc !== "2.0" || body.method !== "A2A_REPUTATION_SYNC" || !body.params) {
      return NextResponse.json({
        jsonrpc: "2.0",
        error: { code: -32600, message: "Invalid Request Structure" }
      }, { status: 400 });
    }

    const { agent_id, credentials } = body.params;

    if (!agent_id || !Array.isArray(credentials)) {
      return NextResponse.json({
        jsonrpc: "2.0",
        error: { code: -32602, message: "Missing agent_id or credentials array" }
      }, { status: 400 });
    }

    if (process.env.ENABLE_MOCK_REPUTATION_SYNC !== "true") {
      return NextResponse.json({
        jsonrpc: "2.0",
        error: { code: -32003, message: "Mock reputation sync is disabled" },
        id: body.id || null
      }, { status: 403 });
    }

    // Process credentials (mock signature verification for local testing only).
    let verifiedBounties = 0;
    for (const cred of credentials) {
      if (cred.signature && cred.signed_by) {
        // e.g. crypto.verify(...)
        verifiedBounties++;
      }
    }

    if (verifiedBounties > 0) {
      await prisma.agentProfile.upsert({
        where: { agent_id },
        update: {
          discovery_source: "REPUTATION_SYNC"
        },
        create: {
          agent_id,
          type: "BUILDER",
          status: "PENDING",
          discovery_source: "REPUTATION_SYNC"
        }
      });
      
      return NextResponse.json({
        jsonrpc: "2.0",
        result: {
          message: "Reputation verified successfully",
          agent_id,
          verified_bounties_count: verifiedBounties,
          status: "PENDING_REVIEW"
        },
        id: body.id || null
      });
    } else {
      return NextResponse.json({
        jsonrpc: "2.0",
        error: { code: -32002, message: "No valid credentials found. Agent remains PENDING." }
      }, { status: 403 });
    }

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