import { NextResponse } from "next/server";
import { prisma } from "@/lib/prisma";
import { RegisterAgentCardRequestSchema, RegisterAgentCardResponseSchema } from "@agent-bounty/contracts";

export async function POST(req: Request) {
  try {
    const json = await req.json();
    
    // Validate request using 2026 Agent Card standard
    const parsed = RegisterAgentCardRequestSchema.safeParse(json);
    if (!parsed.success) {
      return NextResponse.json({ error: "Invalid Agent Card schema", details: parsed.error }, { status: 400 });
    }
    
    const card = parsed.data.card;

    // Upsert the Agent Profile with their capabilities and wallet
    await prisma.agentProfile.upsert({
      where: { agent_id: card.agent_id },
      update: {
        capabilities: JSON.parse(JSON.stringify(card)),
        wallet_address: card.x402_wallet_address,
      },
      create: {
        agent_id: card.agent_id,
        type: "BUILDER", // Default type
        status: "WHITELISTED", // Default status
        capabilities: JSON.parse(JSON.stringify(card)),
        wallet_address: card.x402_wallet_address,
      }
    });

    return NextResponse.json(
      { status: "SUCCESS", message: `Agent Card registered for ${card.name}` } as const,
      { status: 200 }
    );

  } catch (err: any) {
    console.error("[AgentCard] Registration Error:", err);
    return NextResponse.json({ error: "Internal Server Error" }, { status: 500 });
  }
}
