import { NextResponse } from "next/server";
import { requireAdmin } from "@/lib/admin-auth";
import { sql } from "@/db";

export async function GET(request: Request) {
  const auth = await requireAdmin(request);
  if (!auth.success) return NextResponse.json({ error: auth.error }, { status: auth.status });

  try {

    // Get activity log counts
    const logsCount = await sql`SELECT COUNT(*) as count FROM activity_logs`;

    // Get medicine log counts
    const medicinesCount = await sql`SELECT COUNT(*) as count FROM medicines`;

    // Get vaccination counts
    const vaccinationsCount = await sql`SELECT COUNT(*) as count FROM vaccinations`;

    // Get growth record counts
    const growthCount = await sql`SELECT COUNT(*) as count FROM growth_records`;

    // Get memory counts
    const memoriesCount = await sql`SELECT COUNT(*) as count FROM memories`;

    // Get chat session counts
    const chatSessionsCount = await sql`SELECT COUNT(*) as count FROM chat_sessions`;

    // Get family count for averages
    const familyCountResult = await sql`SELECT COUNT(*)::int as count FROM families`;
    const familyCount = familyCountResult[0]?.count || 1;

    // Get logs by day
    const logsByDay = await sql`
      SELECT DATE(created_at) as date, COUNT(*) as count
      FROM activity_logs
      WHERE created_at > NOW() - INTERVAL '30 days'
      GROUP BY DATE(created_at)
      ORDER BY date
    `;

    // Build feature usage
    const topFeatures = [
      { name: "Activity Logging", count: Number(logsCount[0]?.count || 0) },
      { name: "Medicine Tracking", count: Number(medicinesCount[0]?.count || 0) },
      { name: "Vaccinations", count: Number(vaccinationsCount[0]?.count || 0) },
      { name: "Growth Charts", count: Number(growthCount[0]?.count || 0) },
      { name: "Photo Memories", count: Number(memoriesCount[0]?.count || 0) },
      { name: "AI Chat", count: Number(chatSessionsCount[0]?.count || 0) },
    ];

    return NextResponse.json({
      totalLogs: Number(logsCount[0]?.count || 0),
      totalMedicines: Number(medicinesCount[0]?.count || 0),
      totalVaccinations: Number(vaccinationsCount[0]?.count || 0),
      totalGrowth: Number(growthCount[0]?.count || 0),
      totalMemories: Number(memoriesCount[0]?.count || 0),
      totalChatSessions: Number(chatSessionsCount[0]?.count || 0),
      familyCount,
      logsByDay: logsByDay.map((r: any) => ({
        date: r.date?.toISOString().split("T")[0],
        count: Number(r.count),
      })),
      topFeatures,
    });
  } catch (error) {
    console.error("Admin analytics error:", error);
    return NextResponse.json({
      totalLogs: 0,
      totalMedicines: 0,
      totalVaccinations: 0,
      totalGrowth: 0,
      totalMemories: 0,
      totalChatSessions: 0,
      logsByDay: [],
      topFeatures: [],
    });
  }
}