import "server-only"

import { eq } from "drizzle-orm"

import { db } from "@/shared/db"
import {
  homeworkAnswers,
  homeworkAssignmentQuestions,
  homeworkAssignments,
  homeworkSubmissions,
} from "@/shared/db/schema"
import { getExamSubjectIdMap } from "@/modules/exams/data-access"

/**
 * 错题采集所需的答案数据（单题）
 */
export type AnswerForErrorCollection = {
  questionId: string
  answerContent: unknown
  score: number | null
  feedback: string | null
  maxScore: number
}

/**
 * 作业提交的错题采集数据
 */
export type HomeworkSubmissionDataForErrorCollection = {
  assignmentId: string
  subjectId: string | null
  answers: AnswerForErrorCollection[]
}

/**
 * 跨模块接口：获取作业提交的错题采集数据。
 *
 * 供 error-book 模块调用，避免 error-book 直接查询 homeworkSubmissions、
 * homeworkAssignments、homeworkAnswers、homeworkAssignmentQuestions 等属于
 * homework 模块的表，以及 exams 表（通过 exams 模块的 getExamSubjectIdMap 获取）。
 *
 * 返回该提交的所有答案（含得分、反馈、满分），由 error-book 模块
 * 自行筛选错题（score < maxScore）并采集。
 *
 * @param submissionId 作业提交 ID
 * @returns 提交数据；若提交不存在则返回 null
 */
export async function getHomeworkSubmissionDataForErrorCollection(
  submissionId: string,
): Promise<HomeworkSubmissionDataForErrorCollection | null> {
  const submission = await db.query.homeworkSubmissions.findFirst({
    where: eq(homeworkSubmissions.id, submissionId),
    columns: { id: true, assignmentId: true },
  })

  if (!submission) return null

  // 并行获取作业信息、提交答案、题目满分
  const [assignment, answers, hwQuestionScores] = await Promise.all([
    db.query.homeworkAssignments.findFirst({
      where: eq(homeworkAssignments.id, submission.assignmentId),
      columns: { id: true, sourceExamId: true },
    }),
    db
      .select({
        questionId: homeworkAnswers.questionId,
        answerContent: homeworkAnswers.answerContent,
        score: homeworkAnswers.score,
        feedback: homeworkAnswers.feedback,
      })
      .from(homeworkAnswers)
      .where(eq(homeworkAnswers.submissionId, submissionId)),
    db
      .select({
        questionId: homeworkAssignmentQuestions.questionId,
        maxScore: homeworkAssignmentQuestions.score,
      })
      .from(homeworkAssignmentQuestions)
      .where(eq(homeworkAssignmentQuestions.assignmentId, submission.assignmentId)),
  ])

  // 获取学科 ID：若作业派生自试卷，从源试卷获取 subjectId
  let subjectId: string | null = null
  if (assignment?.sourceExamId) {
    const subjectIdMap = await getExamSubjectIdMap([assignment.sourceExamId])
    subjectId = subjectIdMap.get(assignment.sourceExamId) ?? null
  }

  const maxScoreMap = new Map(hwQuestionScores.map((q) => [q.questionId, q.maxScore ?? 0]))

  const mappedAnswers: AnswerForErrorCollection[] = answers.map((a) => ({
    questionId: a.questionId,
    answerContent: a.answerContent,
    score: a.score,
    feedback: a.feedback,
    maxScore: maxScoreMap.get(a.questionId) ?? 0,
  }))

  return {
    assignmentId: submission.assignmentId,
    subjectId,
    answers: mappedAnswers,
  }
}

/**
 * 跨模块接口：获取作业提交的答案数据（供 diagnostic 模块更新掌握度使用）。
 *
 * 返回格式与 exams 模块的 `getExamSubmissionWithAnswers` 一致，
 * 便于 diagnostic 模块统一处理考试提交和作业提交的掌握度更新。
 *
 * @param submissionId 作业提交 ID
 * @returns `{ studentId, answers: Array<{ questionId, score }> }`；若提交不存在则返回 null
 */
export async function getHomeworkSubmissionWithAnswersForMastery(
  submissionId: string,
): Promise<{ studentId: string; answers: Array<{ questionId: string; score: number | null }> } | null> {
  const submission = await db.query.homeworkSubmissions.findFirst({
    where: eq(homeworkSubmissions.id, submissionId),
    columns: { studentId: true },
  })

  if (!submission) return null

  const answers = await db
    .select({
      questionId: homeworkAnswers.questionId,
      score: homeworkAnswers.score,
    })
    .from(homeworkAnswers)
    .where(eq(homeworkAnswers.submissionId, submissionId))

  return {
    studentId: submission.studentId,
    answers,
  }
}
