import "server-only"

import { requirePermission } from "@/shared/lib/auth-guard"
import { Permissions } from "@/shared/types/permissions"
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"

/**
 * 管理员仪表盘流式数据源（P2-1 修复）
 *
 * 返回各独立数据源的 Promise（未解析），供各分区组件用 React `use()` 独立消费。
 * 页面外壳可立即渲染，各分区按各自数据到达顺序流式填充，互不阻塞。
 *
 * 权限校验在此函数内完成（同步阻塞），返回后各 Promise 并行执行。
 */
export async function getAdminDashboardStreams() {
  const ctx = await requirePermission(Permissions.DASHBOARD_ADMIN_READ)
  const scope = ctx.dataScope

  return {
    usersStats: getUsersDashboardStats(),
    classesStats: getClassesDashboardStats(),
    textbooksStats: getTextbooksDashboardStats(),
    questionsStats: getQuestionsDashboardStats(),
    examsStats: getExamsDashboardStats(scope),
    homeworkStats: getHomeworkDashboardStats(scope),
  }
}

export type AdminDashboardStreams = Awaited<ReturnType<typeof getAdminDashboardStreams>>
