import "server-only"

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

import type { DataScope } from "@/shared/types/permissions"
import { exportToExcel } from "@/shared/lib/excel"

import { getAttendanceRecords, getAttendanceStats } from "./data-access"
import { isAttendanceStatus } from "@/shared/constants/attendance-status"

/**
 * 导出考勤记录到 Excel
 * Sheet 1: 考勤明细
 * Sheet 2: 统计汇总
 */
export async function exportAttendanceRecordsToExcel(params: {
  scope: DataScope
  currentUserId?: string
  classId?: string
  status?: string
  date?: string
}): Promise<Buffer> {
  const t = await getTranslations("attendance")

  // 使用类型守卫替代 as 断言（P1-6 修复）；复用 shared 层 isAttendanceStatus
  const status = isAttendanceStatus(params.status) ? params.status : undefined

  const records = await getAttendanceRecords({
    scope: params.scope,
    currentUserId: params.currentUserId,
    classId: params.classId,
    status,
    date: params.date,
  })

  const detailRows = records.items.map((r) => ({
    [t("list.columns.student")]: r.studentName,
    [t("list.columns.class")]: r.className,
    [t("list.columns.date")]: r.date,
    [t("list.columns.status")]: t(`status.${r.status}`),
    [t("list.columns.reason")]: r.reason ?? "",
    [t("list.columns.remark")]: r.remark ?? "",
    [t("list.columns.recorder")]: r.recorderName,
    [t("list.columns.createdAt")]: r.createdAt.split("T")[0],
  }))

  const stats = await getAttendanceStats({
    scope: params.scope,
    currentUserId: params.currentUserId ?? "",
    classId: params.classId,
    date: params.date,
  })

  const statsRows = [
    { metric: t("stats.totalRecords"), value: stats.total },
    { metric: t("stats.present"), value: stats.present },
    { metric: t("stats.absent"), value: stats.absent },
    { metric: t("stats.late"), value: stats.late },
    { metric: t("stats.earlyLeave"), value: stats.earlyLeave },
    { metric: t("stats.excused"), value: stats.excused },
    { metric: t("stats.schoolActivity"), value: stats.schoolActivity },
    { metric: t("stats.attendanceRate"), value: `${stats.presentRate.toFixed(1)}%` },
  ]

  return exportToExcel({
    sheets: [
      {
        name: t("title.adminOverview"),
        columns: [
          { header: t("list.columns.student"), key: t("list.columns.student"), width: 18 },
          { header: t("list.columns.class"), key: t("list.columns.class"), width: 18 },
          { header: t("list.columns.date"), key: t("list.columns.date"), width: 14 },
          { header: t("list.columns.status"), key: t("list.columns.status"), width: 12 },
          { header: t("list.columns.reason"), key: t("list.columns.reason"), width: 24 },
          { header: t("list.columns.remark"), key: t("list.columns.remark"), width: 24 },
          { header: t("list.columns.recorder"), key: t("list.columns.recorder"), width: 16 },
          { header: t("list.columns.createdAt"), key: t("list.columns.createdAt"), width: 14 },
        ],
        rows: detailRows,
      },
      {
        name: t("actions.stats"),
        columns: [
          { header: t("stats.totalRecords"), key: "metric", width: 24 },
          { header: t("stats.attendanceRate"), key: "value", width: 16 },
        ],
        rows: statsRows,
      },
    ],
  })
}
