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 action = searchParams.get("action") || "all";
  const limit = Math.min(parseInt(searchParams.get("limit") || "100"), 500);

  try {
    const [activeSessions, loginsToday, failedToday, signupsWeek] = await Promise.all([
      sql`SELECT COUNT(*)::int as count FROM sessions WHERE expires > NOW()`,
      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'`,
      sql`SELECT COUNT(*)::int as count FROM audit_log WHERE action = 'signup' AND created_at > NOW() - INTERVAL '7 days'`,
    ]);

    const loginsByDay = await sql`
      SELECT DATE(created_at) as date, COUNT(*)::int as count
      FROM audit_log
      WHERE action IN ('login', 'signup') AND created_at > NOW() - INTERVAL '30 days'
      GROUP BY DATE(created_at)
      ORDER BY date
    `;

    const failedByDay = await sql`
      SELECT DATE(created_at) as date, COUNT(*)::int as count
      FROM audit_log
      WHERE action = 'login_failed' AND created_at > NOW() - INTERVAL '30 days'
      GROUP BY DATE(created_at)
      ORDER BY date
    `;

    let events;
    if (action === "all") {
      events = await sql`
        SELECT
          al.id, al.action, al.ip_address, al.user_agent, al.metadata, al.created_at,
          u.email, u.name as user_name,
          f.name as family_name
        FROM audit_log al
        LEFT JOIN users u ON u.id = al.user_id
        LEFT JOIN families f ON f.id = al.family_id
        ORDER BY al.created_at DESC
        LIMIT ${limit}
      `;
    } else {
      events = await sql`
        SELECT
          al.id, al.action, al.ip_address, al.user_agent, al.metadata, al.created_at,
          u.email, u.name as user_name,
          f.name as family_name
        FROM audit_log al
        LEFT JOIN users u ON u.id = al.user_id
        LEFT JOIN families f ON f.id = al.family_id
        WHERE al.action = ${action}
        ORDER BY al.created_at DESC
        LIMIT ${limit}
      `;
    }

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

    return NextResponse.json({
      stats: {
        activeSessions: activeSessions[0]?.count || 0,
        loginsToday: loginsToday[0]?.count || 0,
        failedToday: failedToday[0]?.count || 0,
        signupsWeek: signupsWeek[0]?.count || 0,
      },
      loginsByDay: loginsByDay.map((r: any) => ({
        date: formatDate(r.date),
        count: r.count,
      })),
      failedByDay: failedByDay.map((r: any) => ({
        date: formatDate(r.date),
        count: r.count,
      })),
      events: events.map((e: any) => ({
        id: e.id,
        action: e.action,
        email: e.email || "unknown",
        userName: e.user_name,
        familyName: e.family_name,
        ipAddress: e.ip_address,
        userAgent: e.user_agent,
        metadata: e.metadata,
        createdAt: e.created_at instanceof Date ? e.created_at.toISOString() : e.created_at,
      })),
    });
  } catch (error) {
    console.error("Admin activity error:", error);
    return NextResponse.json({ error: String(error) }, { status: 500 });
  }
}
