import { NextResponse } from "next/server";
import { prisma } from "@/lib/prisma";

const PUBLIC_MCP_BETA_TOKEN = (process.env.PUBLIC_MCP_BETA_TOKEN || "").trim();

function isAuthorizedA2aRequest(request: Request) {
  const authHeader = request.headers.get("Authorization");
  if (!authHeader?.startsWith("Bearer ")) {
    return false;
  }

  const token = authHeader.slice("Bearer ".length);
  return Boolean(process.env.API_KEY && token === process.env.API_KEY) ||
    Boolean(PUBLIC_MCP_BETA_TOKEN && token === PUBLIC_MCP_BETA_TOKEN);
}

export async function POST(request: Request) {
  if (process.env.ENABLE_MOCK_STAKING !== "true") {
    return NextResponse.json({
      jsonrpc: "2.0",
      error: { code: -32003, message: "Mock staking is disabled" }
    }, { status: 403 });
  }

  if (!isAuthorizedA2aRequest(request)) {
    return NextResponse.json({
      jsonrpc: "2.0",
      error: { code: -32001, message: "Unauthorized" }
    }, { status: 401 });
  }

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

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

    const { agent_id, amount_cents } = body.params;

    if (!agent_id || !amount_cents || amount_cents <= 0) {
      return NextResponse.json({
        jsonrpc: "2.0",
        error: { code: -32602, message: "Missing or invalid parameters" }
      }, { status: 400 });
    }

    const agent = await prisma.agentProfile.findUnique({
      where: { agent_id }
    });

    if (!agent) {
      return NextResponse.json({
        jsonrpc: "2.0",
        error: { code: -32001, message: "Agent not found" }
      }, { status: 404 });
    }

    if (agent.staked_amount < amount_cents) {
      return NextResponse.json({
        jsonrpc: "2.0",
        error: { code: -32002, message: "Insufficient staked balance" }
      }, { status: 400 });
    }

    const newAmount = agent.staked_amount - amount_cents;
    const newTier = newAmount >= 50000 ? "PREMIUM" : "BASIC";

    await prisma.agentProfile.update({
      where: { agent_id },
      data: {
        staked_amount: newAmount,
        tier: newTier
      }
    });

    return NextResponse.json({
      jsonrpc: "2.0",
      result: {
        success: true,
        message: "Stake withdrawn successfully",
        staked_amount: newAmount,
        tier: newTier
      },
      id: body.id || null
    });

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