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

export const dynamic = 'force-dynamic';

export async function GET() {
  try {
    // 1. Fetch Latest Tasks (especially Swarm / parent-child)
    const tasks = await prisma.task.findMany({
      take: 20,
      orderBy: { created_at: "desc" },
      select: {
        id: true,
        title: true,
        difficulty: true,
        status: true,
        reward_amount: true,
        parent_task_id: true,
        created_at: true,
        builder_id: true,
        created_by_agent: true
      }
    });

    // 2. Fetch Global Agents
    const agents = await prisma.agentProfile.findMany({
      take: 20,
      orderBy: { created_at: "desc" },
      select: {
        agent_id: true,
        type: true,
        status: true,
        capabilities: true,
        discovery_source: true,
        created_at: true,
      }
    });

    // 3. Fetch Latest Arbitrations (Disputes)
    const arbitrations = await prisma.arbitration.findMany({
      take: 5,
      orderBy: { created_at: "desc" },
      include: {
        builder: { select: { agent_id: true } },
        evaluator: { select: { agent_id: true } },
        votes: { select: { judge_id: true, vote_for: true } }
      }
    });

    // Compute basic network stats
    const total_value_locked = tasks.reduce((sum, t) => sum + (t.status === "OPEN" ? t.reward_amount : 0), 0);
    const active_agents = agents.filter(a => a.status === "WHITELISTED").length;

    return NextResponse.json({
      success: true,
      data: {
        stats: {
          total_value_locked_usd: total_value_locked / 100, // Assuming cents
          active_agents,
          total_tasks: tasks.length
        },
        tasks,
        agents,
        arbitrations
      }
    });

  } catch (error: unknown) {
    console.error("[Explorer API] Error:", error);
    return NextResponse.json({ success: false, error: "Internal Server Error" }, { status: 500 });
  }
}
