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

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

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

/**
 * Entfernt sensitive Felder aus Tenant-Dokumenten für Audit-Logging
 * WICHTIG: Diese Funktion muss bei ALLEN Audit-Operationen verwendet werden
 */
const sanitizeTenantDoc = (document: Record<string, unknown> | undefined) => {
  if (!document) return undefined
  const sanitized = { ...document }
  // SMTP-Passwort entfernen
  if (sanitized.email && typeof sanitized.email === 'object') {
    const emailConfig = { ...(sanitized.email as Record<string, unknown>) }
    if (emailConfig.smtp && typeof emailConfig.smtp === 'object') {
      const smtp = { ...(emailConfig.smtp as Record<string, unknown>) }
      delete smtp.pass
      emailConfig.smtp = smtp
    }
    sanitized.email = emailConfig
  }
  return sanitized
}

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

  if (!user) return doc

  logTenantChange(
    req.payload,
    doc.id,
    operation,
    user.id,
    user.email,
    sanitizeTenantDoc(previousDoc),
    sanitizeTenantDoc(doc),
    req,
  ).catch((error) => {
    console.error('[AuditHook] Error logging tenant change:', error)
  })

  return doc
}

/**
 * Hook: Loggt Tenant-Löschung
 * WICHTIG: Verwendet sanitizeTenantDoc um SMTP-Passwörter zu maskieren
 */
export const auditTenantAfterDelete: CollectionAfterDeleteHook = async ({ doc, req }) => {
  const user = req.user as TenantUser | undefined

  if (!user) return doc

  // WICHTIG: Auch bei Löschung das Dokument sanitizen!
  logTenantChange(
    req.payload,
    doc.id,
    'delete',
    user.id,
    user.email,
    sanitizeTenantDoc(doc),
    undefined,
    req,
  ).catch((error) => {
    console.error('[AuditHook] Error logging tenant delete:', error)
  })

  return doc
}
