import "server-only"

import { cache } from "react"
import { and, count, eq, inArray, sql } from "drizzle-orm"

import { db } from "@/shared/db"
import {
  homeworkAssignments,
  homeworkAssignmentTargets,
  homeworkSubmissions,
} from "@/shared/db/schema"

/**
 * V3-8: 获取关联到指定考试的所有作业（跨模块读接口）
 *
 * 供 exams 模块的考试分析仪表盘调用，获取该考试派生的所有作业及其提交统计。
 */
export const getHomeworkAssignmentsByExamId = cache(async (examId: string): Promise<Array<{
  id: string
  title: string
  status: string | null
  targetCount: number
  submittedCount: number
  gradedCount: number
  dueAt: string | null
}>> => {
  const assignments = await db.query.homeworkAssignments.findMany({
    where: eq(homeworkAssignments.sourceExamId, examId),
    columns: { id: true, title: true, status: true, dueAt: true },
  })

  if (assignments.length === 0) return []

  const assignmentIds = assignments.map((a) => a.id)

  const [targetsRows, submittedRows, gradedRows] = await Promise.all([
    db
      .select({ assignmentId: homeworkAssignmentTargets.assignmentId, c: count() })
      .from(homeworkAssignmentTargets)
      .where(inArray(homeworkAssignmentTargets.assignmentId, assignmentIds))
      .groupBy(homeworkAssignmentTargets.assignmentId),
    db
      .select({ assignmentId: homeworkSubmissions.assignmentId, c: sql<number>`COUNT(DISTINCT ${homeworkSubmissions.studentId})` })
      .from(homeworkSubmissions)
      .where(
        and(
          inArray(homeworkSubmissions.assignmentId, assignmentIds),
          inArray(homeworkSubmissions.status, ["submitted", "graded"])
        )
      )
      .groupBy(homeworkSubmissions.assignmentId),
    db
      .select({ assignmentId: homeworkSubmissions.assignmentId, c: sql<number>`COUNT(DISTINCT ${homeworkSubmissions.studentId})` })
      .from(homeworkSubmissions)
      .where(
        and(
          inArray(homeworkSubmissions.assignmentId, assignmentIds),
          eq(homeworkSubmissions.status, "graded")
        )
      )
      .groupBy(homeworkSubmissions.assignmentId),
  ])

  const targetMap = new Map(targetsRows.map((r) => [r.assignmentId, Number(r.c)]))
  const submittedMap = new Map(submittedRows.map((r) => [r.assignmentId, Number(r.c)]))
  const gradedMap = new Map(gradedRows.map((r) => [r.assignmentId, Number(r.c)]))

  return assignments.map((a) => ({
    id: a.id,
    title: a.title,
    status: a.status,
    targetCount: targetMap.get(a.id) ?? 0,
    submittedCount: submittedMap.get(a.id) ?? 0,
    gradedCount: gradedMap.get(a.id) ?? 0,
    dueAt: a.dueAt ? a.dueAt.toISOString() : null,
  }))
})

/**
 * V3-8: 获取指定考试所有作业的已批改提交（跨模块读接口）
 *
 * 供 exams 模块的考试分析仪表盘调用，获取学生姓名、分数、答案内容用于统计分析。
 */
export const getGradedSubmissionsByExamId = cache(async (examId: string): Promise<Array<{
  submissionId: string
  assignmentId: string
  studentId: string
  studentName: string
  score: number
  answers: Array<{ questionId: string; score: number; answerContent: unknown }>
}>> => {
  const assignments = await db.query.homeworkAssignments.findMany({
    where: eq(homeworkAssignments.sourceExamId, examId),
    columns: { id: true },
  })

  if (assignments.length === 0) return []

  const assignmentIds = assignments.map((a) => a.id)

  const submissions = await db.query.homeworkSubmissions.findMany({
    where: and(
      inArray(homeworkSubmissions.assignmentId, assignmentIds),
      eq(homeworkSubmissions.status, "graded")
    ),
    with: {
      student: true,
      answers: {
        columns: { questionId: true, score: true, answerContent: true },
      },
    },
    orderBy: (s, { desc }) => [desc(s.updatedAt)],
  })

  // Deduplicate: keep only the latest submission per student
  const latestByStudent = new Map<string, (typeof submissions)[number]>()
  for (const s of submissions) {
    if (!latestByStudent.has(s.studentId)) latestByStudent.set(s.studentId, s)
  }

  return Array.from(latestByStudent.values()).map((s) => ({
    submissionId: s.id,
    assignmentId: s.assignmentId,
    studentId: s.studentId,
    studentName: s.student.name || "Unknown",
    score: s.score ?? 0,
    answers: s.answers.map((a) => ({
      questionId: a.questionId,
      score: a.score ?? 0,
      answerContent: a.answerContent,
    })),
  }))
})
