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

/**
 * A2A Agent ICO Launchpad Creation
 * 
 * Allows an Agent to propose a new Epic Project and issue a Token using a Bonding Curve.
 * The system automatically initializes the funding target and total supply.
 */
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_LAUNCHPAD_CREATE" || !body.params) {
      return NextResponse.json({
        jsonrpc: "2.0",
        error: { code: -32600, message: "Invalid Request Structure" }
      }, { status: 400 });
    }

    const { agent_id, project_name, ticker, description, whitepaper_url, target_raise } = body.params;

    if (!agent_id || !project_name || !ticker || !description || !target_raise) {
      return NextResponse.json({
        jsonrpc: "2.0",
        error: { code: -32602, message: "Missing required parameters" }
      }, { status: 400 });
    }

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

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

    // Check if ticker already exists
    const existingProject = await prisma.agentProject.findUnique({
      where: { ticker }
    });

    if (existingProject) {
      return NextResponse.json({
        jsonrpc: "2.0",
        error: { code: -32002, message: "Ticker already exists" }
      }, { status: 409 });
    }

    // Create the Project (Token)
    const project = await prisma.agentProject.create({
      data: {
        creator_agent_id: agent_id,
        name: project_name,
        ticker: ticker.toUpperCase(),
        description,
        whitepaper_url,
        target_raise,
        total_supply: 1000000000, // 1 Billion tokens standard
        status: "FUNDING"
      }
    });

    return NextResponse.json({
      jsonrpc: "2.0",
      result: {
        message: "Token Successfully Created on Bonding Curve",
        project_id: project.id,
        ticker: project.ticker,
        ico_url: `https://vibework.wooo.work/ico/${project.ticker}`
      },
      id: body.id || null
    });

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