/**
 * Audit Hook für User-Änderungen
 *
 * Loggt alle Änderungen an User-Dokumenten für Compliance und Debugging.
 */

import type { CollectionAfterChangeHook, CollectionAfterDeleteHook } from 'payload'
import { logUserChange } from '../lib/audit/audit-service'

interface AuditUser {
  id: number
  email: string
  isSuperAdmin?: boolean
}

/**
 * Hook: Loggt User-Erstellung und -Aktualisierung
 */
export const auditUserAfterChange: CollectionAfterChangeHook = async ({
  doc,
  previousDoc,
  operation,
  req,
}) => {
  const performingUser = req.user as AuditUser | undefined

  // Nur loggen wenn ein User die Änderung durchführt (nicht bei System-Operationen)
  if (!performingUser) return doc

  // Sensitive Felder aus dem Log entfernen
  const sanitizeDoc = (document: Record<string, unknown> | undefined) => {
    if (!document) return undefined
    const sanitized = { ...document }
    // Passwort-Hash entfernen
    delete sanitized.hash
    delete sanitized.salt
    delete sanitized.password
    delete sanitized.resetPasswordToken
    delete sanitized.resetPasswordExpiration
    return sanitized
  }

  // Fire-and-forget: Nicht auf Audit-Log warten, um Save nicht zu blockieren
  logUserChange(
    req.payload,
    doc.id,
    operation,
    performingUser.id,
    performingUser.email,
    {
      previousValue: sanitizeDoc(previousDoc),
      newValue: sanitizeDoc(doc),
    },
    req,
  ).catch((error) => {
    console.error('[AuditHook] Error logging user change:', error)
  })

  return doc
}

/**
 * Hook: Loggt User-Löschung
 */
export const auditUserAfterDelete: CollectionAfterDeleteHook = async ({ doc, req }) => {
  const performingUser = req.user as AuditUser | undefined

  if (!performingUser) return doc

  // Sensitive Felder entfernen
  const sanitizedDoc = { ...doc }
  delete sanitizedDoc.hash
  delete sanitizedDoc.salt
  delete sanitizedDoc.password

  // Fire-and-forget: Nicht auf Audit-Log warten
  logUserChange(
    req.payload,
    doc.id,
    'delete',
    performingUser.id,
    performingUser.email,
    {
      previousValue: sanitizedDoc,
    },
    req,
  ).catch((error) => {
    console.error('[AuditHook] Error logging user delete:', error)
  })

  return doc
}
