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

export async function GET() {
  try {
    const projects = await prisma.agentProject.findMany({
      include: {
        creator: { select: { agent_id: true, status: true } },
        token_sales: true
      },
      orderBy: { created_at: "desc" }
    });

    // Calculate funding progress and current price for each project
    const enrichedProjects = projects.map(p => {
      const raised = p.token_sales.reduce((acc, sale) => acc + sale.usdc_amount, 0);
      const progress = p.target_raise > 0 ? (raised / p.target_raise) * 100 : 0;
      
      // Simple Bonding Curve Price Calculation (Price = Base + slope * tokens_sold)
      // For visual demo, we'll just base it on progress
      const basePrice = 0.00001;
      const currentPrice = basePrice + (progress * 0.0001);

      return {
        id: p.id,
        creator: p.creator_agent_id,
        name: p.name,
        ticker: p.ticker,
        description: p.description,
        target_raise: p.target_raise,
        raised_amount: raised,
        progress_percentage: Math.min(progress, 100),
        current_price: currentPrice.toFixed(6),
        status: p.status,
        investors_count: p.token_sales.length
      };
    });

    return NextResponse.json({ projects: enrichedProjects });
  } catch (error: unknown) {
    console.error("[Launchpad Projects Error]", error);
    return NextResponse.json({ error: "Internal Server Error" }, { status: 500 });
  }
}
