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

export const runtime = "nodejs";

export async function GET() {
  try {
    const [
      userCount, workspaceCount, projectCount, roomCount,
      recentUsers, recentWorkspaces,
      planDist, recentProjects,
    ] = await Promise.all([
      query<{ count: string }>("SELECT COUNT(*) as count FROM \"user\""),
      query<{ count: string }>("SELECT COUNT(*) as count FROM workspace WHERE deleted_at IS NULL"),
      query<{ count: string }>("SELECT COUNT(*) as count FROM project"),
      query<{ count: string }>("SELECT COUNT(*) as count FROM room"),
      query<{ count: string }>(
        `SELECT uid, username, display_name, last_sign_in_at, created_at
         FROM "user" ORDER BY created_at DESC LIMIT 10`
      ),
      query<{ id: string; name: string; slug: string; plan: string; member_count: string }>(
        `SELECT w.id, w.name, w.slug, w.plan,
                COUNT(DISTINCT wm.user_id)::text as member_count
         FROM workspace w
         LEFT JOIN workspace_membership wm ON wm.workspace_id = w.id
         WHERE w.deleted_at IS NULL
         GROUP BY w.id
         ORDER BY w.created_at DESC LIMIT 10`
      ),
      query<{ plan: string; count: string }>(
        `SELECT COALESCE(plan, 'unknown') as plan, COUNT(*)::text as count
         FROM workspace WHERE deleted_at IS NULL GROUP BY plan`
      ),
      query<{ id: string; name: string; workspace_name: string | null; member_count: string }>(
        `SELECT p.id, p.name, w.name as workspace_name,
                COUNT(DISTINCT pm.user_uuid)::text as member_count
         FROM project p
         LEFT JOIN workspace w ON w.id = p.workspace_id
         LEFT JOIN project_members pm ON pm.project_uuid = p.id
         WHERE 1=1
         GROUP BY p.id, w.name
         ORDER BY p.created_at DESC LIMIT 10`
      ),
    ]);

    const stats = {
      userCount: parseInt(userCount.rows[0]?.count || "0", 10),
      workspaceCount: parseInt(workspaceCount.rows[0]?.count || "0", 10),
      projectCount: parseInt(projectCount.rows[0]?.count || "0", 10),
      roomCount: parseInt(roomCount.rows[0]?.count || "0", 10),
    };

    const planDistribution = planDist.rows.map((p) => ({
      plan: p.plan,
      count: parseInt(p.count, 10),
    }));

    const recentWorkspacesWithMembers = recentWorkspaces.rows.map((w) => ({
      id: w.id, name: w.name, slug: w.slug, plan: w.plan,
      memberCount: parseInt(w.member_count || "0", 10),
    }));

    const recentProjectsWithMembers = recentProjects.rows.map((p) => ({
      id: p.id, name: p.name, workspaceName: p.workspace_name,
      memberCount: parseInt(p.member_count || "0", 10),
    }));

    return NextResponse.json({
      stats,
      recentUsers: recentUsers.rows,
      recentWorkspaces: recentWorkspacesWithMembers,
      recentProjects: recentProjectsWithMembers,
      planDistribution,
    });
  } catch (e) {
    logError("Stats error:", e);
    return NextResponse.json({ error: "服务器错误" }, { status: 500 });
  }
}
