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

export const runtime = "nodejs";

export async function GET() {
  try {
    // Last 30 days of DAU
    const dauResult = await query<{ date: string; dau: string }>(
      `SELECT
         TO_CHAR(DATE_TRUNC('day', created_at), 'YYYY-MM-DD') AS date,
         COUNT(DISTINCT user_uid) AS dau
       FROM user_activity_log
       WHERE created_at >= NOW() - INTERVAL '30 days'
       GROUP BY DATE_TRUNC('day', created_at)
       ORDER BY date ASC`
    );

    // Last 7 days breakdown by action
    const actionBreakdown = await query<{ date: string; action: string; count: string }>(
      `SELECT
         TO_CHAR(DATE_TRUNC('day', created_at), 'YYYY-MM-DD') AS date,
         action,
         COUNT(*) AS count
       FROM user_activity_log
       WHERE created_at >= NOW() - INTERVAL '7 days'
       GROUP BY DATE_TRUNC('day', created_at), action
       ORDER BY date ASC, action ASC`
    );

    // MAU: unique users in last 30 days
    const mauResult = await query<{ mau: string }>(
      `SELECT COUNT(DISTINCT user_uid) AS mau
       FROM user_activity_log
       WHERE created_at >= NOW() - INTERVAL '30 days'`
    );

    // Total logins (ever)
    const totalLogins = await query<{ count: string }>(
      `SELECT COUNT(*) AS count FROM user_activity_log WHERE action = 'login'`
    );

    // Login stats last 30 days
    const loginStats = await query<{ date: string; logins: string }>(
      `SELECT
         TO_CHAR(DATE_TRUNC('day', created_at), 'YYYY-MM-DD') AS date,
         COUNT(*) AS logins
       FROM user_activity_log
       WHERE action = 'login' AND created_at >= NOW() - INTERVAL '30 days'
       GROUP BY DATE_TRUNC('day', created_at)
       ORDER BY date ASC`
    );

    const dau = dauResult.rows.map((r) => ({
      date: r.date,
      dau: parseInt(r.dau, 10),
    }));

    const mau = parseInt(mauResult.rows[0]?.mau || "0", 10);
    const totalLoginCount = parseInt(totalLogins.rows[0]?.count || "0", 10);
    const logins = loginStats.rows.map((r) => ({
      date: r.date,
      logins: parseInt(r.logins, 10),
    }));

    // Recent activity count (last 24h)
    const last24h = await query<{ count: string }>(
      `SELECT COUNT(*) AS count FROM user_activity_log WHERE created_at >= NOW() - INTERVAL '24 hours'`
    );

    return NextResponse.json({
      dau,
      mau,
      totalLogins: totalLoginCount,
      logins,
      last24h: parseInt(last24h.rows[0]?.count || "0", 10),
    });
  } catch (e) {
    console.error("Activity stats error:", e);
    return NextResponse.json({ error: "服务器错误" }, { status: 500 });
  }
}
