import "server-only"

import { getTranslations } from "next-intl/server"

import { exportToExcel } from "@/shared/lib/excel"

import { getElectiveCourses } from "./data-access"
import { getCourseSelections } from "./data-access-selections"
import {
  ElectiveCourseStatusEnum,
} from "./schema"

/**
 * 导出选修课课程列表到 Excel
 * Sheet 1: 课程明细
 *
 * 注意：通过 Zod 枚举做类型守卫，避免 `as` 类型断言。
 */
export async function exportElectiveCoursesToExcel(params: {
  status?: string
  teacherId?: string
}): Promise<Buffer> {
  const t = await getTranslations("elective")

  // 用 Zod 枚举校验 status，通过则类型收窄为 ElectiveCourseStatus
  const statusParsed = params.status
    ? ElectiveCourseStatusEnum.safeParse(params.status)
    : undefined
  const status = statusParsed?.success ? statusParsed.data : undefined

  const courses = await getElectiveCourses({
    status,
    teacherId: params.teacherId,
  })

  const rows = courses.map((c) => ({
    [t("fields.name")]: c.name,
    [t("fields.teacher")]: c.teacherName ?? "",
    [t("fields.subject")]: c.subjectName ?? "",
    [t("fields.grade")]: c.gradeName ?? "",
    [t("fields.capacity")]: c.capacity,
    [t("fields.enrolled")]: c.enrolledCount,
    [t("fields.classroom")]: c.classroom ?? "",
    [t("fields.schedule")]: c.schedule ?? "",
    [t("fields.credit")]: c.credit,
    [t("fields.selectionMode")]: t(`selectionMode.${c.selectionMode}`),
    [t("export.statusHeader")]: t(`status.${c.status}`),
    [t("fields.startDate")]: c.startDate ?? "",
    [t("fields.endDate")]: c.endDate ?? "",
  }))

  return exportToExcel({
    sheets: [
      {
        name: t("export.courseSheetName"),
        columns: [
          { header: t("fields.name"), key: t("fields.name"), width: 24 },
          { header: t("fields.teacher"), key: t("fields.teacher"), width: 16 },
          { header: t("fields.subject"), key: t("fields.subject"), width: 14 },
          { header: t("fields.grade"), key: t("fields.grade"), width: 12 },
          { header: t("fields.capacity"), key: t("fields.capacity"), width: 10 },
          { header: t("fields.enrolled"), key: t("fields.enrolled"), width: 10 },
          { header: t("fields.classroom"), key: t("fields.classroom"), width: 14 },
          { header: t("fields.schedule"), key: t("fields.schedule"), width: 20 },
          { header: t("fields.credit"), key: t("fields.credit"), width: 8 },
          { header: t("fields.selectionMode"), key: t("fields.selectionMode"), width: 16 },
          { header: t("export.statusHeader"), key: t("export.statusHeader"), width: 12 },
          { header: t("fields.startDate"), key: t("fields.startDate"), width: 14 },
          { header: t("fields.endDate"), key: t("fields.endDate"), width: 14 },
        ],
        rows,
      },
    ],
  })
}

/**
 * 导出课程选课名单到 Excel
 * Sheet 1: 选课名单
 */
export async function exportCourseSelectionsToExcel(params: {
  courseId: string
}): Promise<Buffer> {
  const t = await getTranslations("elective")

  const selections = await getCourseSelections(params.courseId)

  const rows = selections.map((s, idx) => ({
    [t("export.indexHeader")]: idx + 1,
    [t("fields.name")]: s.studentName ?? "",
    [t("export.statusHeader")]: t(`selectionStatus.${s.status}`),
    [t("export.priorityHeader")]: s.priority ?? 1,
    [t("export.selectedAtHeader")]: s.selectedAt.split("T")[0],
    [t("export.enrolledAtHeader")]: s.enrolledAt ? s.enrolledAt.split("T")[0] : "",
  }))

  return exportToExcel({
    sheets: [
      {
        name: t("export.selectionSheetName"),
        columns: [
          { header: t("export.indexHeader"), key: t("export.indexHeader"), width: 6 },
          { header: t("fields.name"), key: t("fields.name"), width: 18 },
          { header: t("export.statusHeader"), key: t("export.statusHeader"), width: 12 },
          { header: t("export.priorityHeader"), key: t("export.priorityHeader"), width: 10 },
          { header: t("export.selectedAtHeader"), key: t("export.selectedAtHeader"), width: 14 },
          { header: t("export.enrolledAtHeader"), key: t("export.enrolledAtHeader"), width: 14 },
        ],
        rows,
      },
    ],
  })
}
