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 });

  const { searchParams } = new URL(request.url);
  const period = parseInt(searchParams.get("period") || "30");

  try {
    const [familyCount, userCount, childCount, tierStats, activeSessionsResult] = await Promise.all([
      sql`SELECT COUNT(*)::int as count FROM families`,
      sql`SELECT COUNT(*)::int as count FROM users`,
      sql`SELECT COUNT(*)::int as count FROM children`,
      sql`SELECT tier, COUNT(*)::int as count FROM families GROUP BY tier`,
      sql`SELECT COUNT(*)::int as count FROM sessions WHERE expires > NOW()`,
    ]);

    const proFamilies = tierStats.find((t: any) => t.tier === "pro")?.count || 0;
    const freeFamilies = tierStats.find((t: any) => t.tier === "free")?.count || 0;
    const totalFamilies = familyCount[0]?.count || 0;
    const mrr = proFamilies * 9.99;

    const [familiesByDay, usersByDay, childrenByAge, recentLogins, failedLogins] = await Promise.all([
      sql`
        SELECT DATE(created_at) as date, COUNT(*)::int as count
        FROM families
        WHERE created_at > NOW() - (${period}::int * INTERVAL '1 day')
        GROUP BY DATE(created_at)
        ORDER BY date
      `,
      sql`
        SELECT DATE(created_at) as date, COUNT(*)::int as count
        FROM users
        WHERE created_at > NOW() - (${period}::int * INTERVAL '1 day')
        GROUP BY DATE(created_at)
        ORDER BY date
      `,
      sql`
        SELECT
          EXTRACT(YEAR FROM AGE(birth_date))::int as age_years,
          COUNT(*)::int as count
        FROM children
        WHERE birth_date IS NOT NULL
        GROUP BY EXTRACT(YEAR FROM AGE(birth_date))::int
        ORDER BY age_years
      `,
      sql`SELECT COUNT(*)::int as count FROM audit_log WHERE action = 'login' AND created_at > NOW() - INTERVAL '24 hours'`,
      sql`SELECT COUNT(*)::int as count FROM audit_log WHERE action = 'login_failed' AND created_at > NOW() - INTERVAL '24 hours'`,
    ]);

    const formatDate = (d: any) =>
      d instanceof Date ? d.toISOString().split("T")[0] : String(d);

    const ageLabel = (years: number) => {
      if (years === 0) return "< 1 yr";
      if (years === 1) return "1 yr";
      return `${years} yrs`;
    };

    return NextResponse.json({
      overview: {
        totalFamilies,
        totalUsers: userCount[0]?.count || 0,
        totalChildren: childCount[0]?.count || 0,
        proFamilies,
        freeFamilies,
        mrr,
        avgRevenuePerUser: totalFamilies > 0 ? parseFloat((mrr / totalFamilies).toFixed(2)) : 0,
        activeSessions: activeSessionsResult[0]?.count || 0,
        loginsLast24h: recentLogins[0]?.count || 0,
        failedLoginsLast24h: failedLogins[0]?.count || 0,
      },
      conversions: {
        freeToPro: proFamilies,
        conversionRate: totalFamilies > 0
          ? parseFloat(((proFamilies / totalFamilies) * 100).toFixed(1))
          : 0,
      },
      growth: {
        familiesByDay: familiesByDay.map((r: any) => ({
          date: formatDate(r.date),
          count: r.count,
        })),
        usersByDay: usersByDay.map((r: any) => ({
          date: formatDate(r.date),
          count: r.count,
        })),
      },
      childrenByAge: childrenByAge.map((r: any) => ({
        ageGroup: ageLabel(r.age_years),
        count: r.count,
      })),
    });
  } catch (error) {
    console.error("Admin stats error:", error);
    return NextResponse.json({ error: String(error) }, { status: 500 });
  }
}
