import type { AfterChangeHook } from 'payload'

import { logDocumentChange } from '@/utilities/auditLogger'

/**
 * 創建稽核日誌 Hook
 * 用於追蹤文件的創建、更新、刪除操作
 */
export const auditChange =
  (collection: string): AfterChangeHook =>
  async ({ doc, req }) => {
    // 跳過 audit 集合本身以避免無限循環
    if (collection === 'audit') return doc

    await logDocumentChange(
      req,
      operation as 'create' | 'update' | 'delete',
      collection,
      doc.id as string,
      (doc.title || doc.name || String(doc.id)) as string,
    )

    return doc
  }

/**
 * 刪除稽核日誌 Hook
 * 用於追蹤文件刪除操作（需要在刪除前記錄標題）
 */
export const auditDelete =
  (collection: string): AfterChangeHook =>
  async ({ doc, req }) => {
    if (collection === 'audit') return doc

    await logDocumentChange(
      req,
      'delete',
      collection,
      doc.id as string,
      (doc.title || doc.name || String(doc.id)) as string,
    )

    return doc
  }

/**
 * Global 稽核日誌 Hook
 * 用於追蹤 Global 配置的變更
 */
export const auditGlobalChange =
  (global: string): AfterChangeHook =>
  async ({ req, previousDoc, doc }) => {
    if (!req.user) return doc

    const { auditLogger } = await import('@/utilities/auditLogger')

    await auditLogger(req, {
      action: 'update',
      collection: `global_${global}`,
      userId: req.user.id,
      userName: req.user.name as string,
      userEmail: req.user.email as string,
      userRole: String(req.user.role ?? ''),
      changes: {
        previous: previousDoc,
        current: doc,
      },
    })

    return doc
  }
