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

export async function GET() {
  try {
    const clinic = await prisma.clinic.findFirst();
    if (!clinic) return NextResponse.json({ nodes: {}, summary: {} });

    /* ── Real appointment / lead data ── */
    const [totalAppts, confirmedAppts, noShows, totalLeads, activeTrees] = await Promise.all([
      prisma.appointment.count({ where: { clinicId: clinic.id } }),
      prisma.appointment.count({ where: { clinicId: clinic.id, status: "confirmed" } }),
      prisma.appointment.count({ where: { clinicId: clinic.id, status: "no_show" } }),
      prisma.lead.count({ where: { clinicId: clinic.id } }),
      prisma.reminderTree.count({ where: { clinicId: clinic.id, isActive: true } }),
    ]);

    /* ── UserJourney stats (if any exist) ── */
    const [totalJourneys, completedJourneys] = await Promise.all([
      prisma.userJourney.count(),
      prisma.userJourney.count({ where: { status: "completed" } }),
    ]);

    /* ── Per-node execution stats from NodeExecution table ── */
    const executions = await prisma.nodeExecution.groupBy({
      by: ["nodeId", "status"],
      _count: { id: true },
    });

    // Build per-node map: { nodeId: { executed, failed, skipped } }
    const nodeStats: Record<string, { executed: number; failed: number; skipped: number }> = {};
    for (const row of executions) {
      if (!nodeStats[row.nodeId]) nodeStats[row.nodeId] = { executed: 0, failed: 0, skipped: 0 };
      if (row.status === "executed") nodeStats[row.nodeId].executed = row._count.id;
      if (row.status === "failed")   nodeStats[row.nodeId].failed   = row._count.id;
      if (row.status === "skipped")  nodeStats[row.nodeId].skipped  = row._count.id;
    }

    /* ── Derive analytics per canvas node (fallback from appointment data) ── */
    // If no journey data, project from appointment counts
    const hasRealData = totalJourneys > 0;
    const baselineSent = hasRealData ? totalJourneys : totalAppts;
    const baselineResp = hasRealData ? completedJourneys : confirmedAppts;

    const summary = {
      hasRealData,
      totalAppts,
      confirmedAppts,
      noShows,
      totalLeads,
      activeTrees,
      totalJourneys,
      completedJourneys,
      confirmRate: totalAppts > 0 ? Math.round((confirmedAppts / totalAppts) * 100) : 0,
      noShowRate:  totalAppts > 0 ? Math.round((noShows / totalAppts) * 100) : 0,
    };

    return NextResponse.json({ nodeStats, summary, baselineSent, baselineResp });
  } catch (err: any) {
    return NextResponse.json({ error: err.message }, { status: 500 });
  }
}
