import "server-only"

import { exportToExcel, type ExcelColumn } from "@/shared/lib/excel"
import { formatDateForFile } from "@/shared/lib/utils"

import type { AuditLog, DataChangeLog, LoginLog } from "./types"

/** 审计日志 Excel 列定义 */
export const AUDIT_LOG_COLUMNS: ExcelColumn[] = [
  { header: "User ID", key: "userId", width: 22 },
  { header: "User Name", key: "userName", width: 18 },
  { header: "Module", key: "module", width: 16 },
  { header: "Action", key: "action", width: 22 },
  { header: "Target ID", key: "targetId", width: 22 },
  { header: "Target Type", key: "targetType", width: 16 },
  { header: "Detail", key: "detail", width: 40 },
  { header: "IP Address", key: "ipAddress", width: 16 },
  { header: "Status", key: "status", width: 10 },
  { header: "Created At", key: "createdAt", width: 22 },
]

/** 登录日志 Excel 列定义 */
export const LOGIN_LOG_COLUMNS: ExcelColumn[] = [
  { header: "User ID", key: "userId", width: 22 },
  { header: "User Email", key: "userEmail", width: 26 },
  { header: "Action", key: "action", width: 12 },
  { header: "Status", key: "status", width: 10 },
  { header: "IP Address", key: "ipAddress", width: 16 },
  { header: "User Agent", key: "userAgent", width: 40 },
  { header: "Error Message", key: "errorMessage", width: 30 },
  { header: "Created At", key: "createdAt", width: 22 },
]

/** 数据变更日志 Excel 列定义 */
export const DATA_CHANGE_LOG_COLUMNS: ExcelColumn[] = [
  { header: "Table Name", key: "tableName", width: 22 },
  { header: "Record ID", key: "recordId", width: 22 },
  { header: "Action", key: "action", width: 10 },
  { header: "Old Value", key: "oldValue", width: 50 },
  { header: "New Value", key: "newValue", width: 50 },
  { header: "Changed By", key: "changedBy", width: 22 },
  { header: "Changed By Name", key: "changedByName", width: 18 },
  { header: "IP Address", key: "ipAddress", width: 16 },
  { header: "Created At", key: "createdAt", width: 22 },
]

/** 将审计日志映射为 Excel 行数据 */
export function mapAuditLogsToRows(
  items: AuditLog[],
): Record<string, unknown>[] {
  return items.map((r) => ({
    userId: r.userId,
    userName: r.userName,
    module: r.module,
    action: r.action,
    targetId: r.targetId ?? "",
    targetType: r.targetType ?? "",
    detail: r.detail ?? "",
    ipAddress: r.ipAddress ?? "",
    status: r.status,
    createdAt: r.createdAt,
  }))
}

/** 将登录日志映射为 Excel 行数据 */
export function mapLoginLogsToRows(
  items: LoginLog[],
): Record<string, unknown>[] {
  return items.map((r) => ({
    userId: r.userId ?? "",
    userEmail: r.userEmail,
    action: r.action,
    status: r.status,
    ipAddress: r.ipAddress ?? "",
    userAgent: r.userAgent ?? "",
    errorMessage: r.errorMessage ?? "",
    createdAt: r.createdAt,
  }))
}

/** 将数据变更日志映射为 Excel 行数据 */
export function mapDataChangeLogsToRows(
  items: DataChangeLog[],
): Record<string, unknown>[] {
  return items.map((r) => ({
    tableName: r.tableName,
    recordId: r.recordId,
    action: r.action,
    oldValue: r.oldValue ?? "",
    newValue: r.newValue ?? "",
    changedBy: r.changedBy,
    changedByName: r.changedByName,
    ipAddress: r.ipAddress ?? "",
    createdAt: r.createdAt,
  }))
}

/** 构建审计日志 Excel 导出 */
export async function buildAuditLogExport(
  items: AuditLog[],
): Promise<{ buffer: Buffer; filename: string }> {
  const buffer = await exportToExcel({
    sheets: [
      {
        name: "Audit Logs",
        columns: AUDIT_LOG_COLUMNS,
        rows: mapAuditLogsToRows(items),
      },
    ],
  })
  return { buffer, filename: `audit_logs_${formatDateForFile()}.xlsx` }
}

/** 构建登录日志 Excel 导出 */
export async function buildLoginLogExport(
  items: LoginLog[],
): Promise<{ buffer: Buffer; filename: string }> {
  const buffer = await exportToExcel({
    sheets: [
      {
        name: "Login Logs",
        columns: LOGIN_LOG_COLUMNS,
        rows: mapLoginLogsToRows(items),
      },
    ],
  })
  return { buffer, filename: `login_logs_${formatDateForFile()}.xlsx` }
}

/** 构建数据变更日志 Excel 导出 */
export async function buildDataChangeLogExport(
  items: DataChangeLog[],
): Promise<{ buffer: Buffer; filename: string }> {
  const buffer = await exportToExcel({
    sheets: [
      {
        name: "Data Change Logs",
        columns: DATA_CHANGE_LOG_COLUMNS,
        rows: mapDataChangeLogsToRows(items),
      },
    ],
  })
  return { buffer, filename: `data_change_logs_${formatDateForFile()}.xlsx` }
}
