import "server-only"

import { cache } from "react"

import { getClassesDashboardStats } from "@/modules/classes/data-access"
import { getExamsDashboardStats } from "@/modules/exams/data-access"
import { getHomeworkDashboardStats } from "@/modules/homework/stats-service"
import { getQuestionsDashboardStats } from "@/modules/questions/data-access"
import { getTextbooksDashboardStats } from "@/modules/textbooks/data-access"
import { getUsersDashboardStats } from "@/modules/users/data-access"
import type { DataScope } from "@/shared/types/permissions"

import type { AdminDashboardData } from "./types"

export const getAdminDashboardData = cache(async (scope?: DataScope): Promise<AdminDashboardData> => {
  const [
    usersStats,
    classesStats,
    textbooksStats,
    questionsStats,
    examsStats,
    homeworkStats,
  ] = await Promise.all([
    getUsersDashboardStats(),
    getClassesDashboardStats(),
    getTextbooksDashboardStats(),
    getQuestionsDashboardStats(),
    getExamsDashboardStats(scope),
    getHomeworkDashboardStats(scope),
  ])

  return {
    activeSessionsCount: usersStats.activeSessionsCount,
    userCount: usersStats.userCount,
    userRoleCounts: usersStats.userRoleCounts,
    classCount: classesStats.classCount,
    textbookCount: textbooksStats.textbookCount,
    chapterCount: textbooksStats.chapterCount,
    questionCount: questionsStats.questionCount,
    examCount: examsStats.examCount,
    homeworkAssignmentCount: homeworkStats.homeworkAssignmentCount,
    homeworkAssignmentPublishedCount: homeworkStats.homeworkAssignmentPublishedCount,
    homeworkSubmissionCount: homeworkStats.homeworkSubmissionCount,
    homeworkSubmissionToGradeCount: homeworkStats.homeworkSubmissionToGradeCount,
    recentUsers: usersStats.recentUsers,
    // TODO(V4-P2-4): 接入真实趋势数据统计查询（按日期聚合用户注册数和作业提交数）
    // 当前为占位空数组，AdminTrendCharts 组件会渲染空状态
    userGrowth: [],
    homeworkTrend: [],
  }
})
