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"

/**
 * 导出考勤记录到 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")

  const records = await getAttendanceRecords({
    scope: params.scope,
    currentUserId: params.currentUserId,
    classId: params.classId,
    status: params.status as
      | "present"
      | "absent"
      | "late"
      | "early_leave"
      | "excused"
      | undefined,
    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.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.totalRecords },
    { metric: t("stats.present"), value: stats.presentCount },
    { metric: t("stats.absent"), value: stats.absentCount },
    { metric: t("stats.late"), value: stats.lateCount },
    { metric: t("stats.earlyLeave"), value: stats.earlyLeaveCount },
    { metric: t("stats.excused"), value: stats.excusedCount },
    { metric: t("stats.attendanceRate"), value: `${stats.attendanceRate}%` },
  ]

  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.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: "Metric", key: "metric", width: 24 },
          { header: "Value", key: "value", width: 16 },
        ],
        rows: statsRows,
      },
    ],
  })
}
