// src/hooks/formSubmissionHooks.ts

import type { CollectionBeforeChangeHook } from 'payload'

interface InternalNote {
  note: string
  author?: number | string | { id: number | string }
  createdAt?: string
}

interface ResponseTracking {
  responded?: boolean
  respondedAt?: string
  respondedBy?: number | string | { id: number | string }
  method?: string
  summary?: string
}

interface FormSubmissionDoc {
  id: number | string
  status?: string
  readAt?: string
  readBy?: number | string | { id: number | string }
  internalNotes?: InternalNote[]
  responseTracking?: ResponseTracking
  [key: string]: unknown
}

/**
 * Hook: Setzt automatisch den Autor und Zeitstempel bei neuen Notizen
 */
export const setNoteMetadata: CollectionBeforeChangeHook<FormSubmissionDoc> = async ({
  data,
  req,
  originalDoc,
}) => {
  if (!data.internalNotes || !req.user) return data

  const originalNotes = originalDoc?.internalNotes || []
  const newNotes = data.internalNotes || []

  // Finde neue Notizen (die noch keinen Autor haben)
  const updatedNotes = newNotes.map((note, index) => {
    const isNew = !note.author && !note.createdAt
    const isExisting = originalNotes[index]

    if (isNew || (!isExisting && !note.author)) {
      return {
        ...note,
        author: req.user?.id,
        createdAt: new Date().toISOString(),
      }
    }

    return note
  })

  return {
    ...data,
    internalNotes: updatedNotes,
  }
}

/**
 * Hook: Markiert Einsendung als gelesen beim ersten Öffnen
 */
export const markAsRead: CollectionBeforeChangeHook<FormSubmissionDoc> = async ({
  data,
  req,
  originalDoc,
  operation,
}) => {
  // Nur beim Update und wenn noch nicht gelesen
  if (operation !== 'update' || !req.user) return data

  // Wenn noch nicht gelesen, jetzt markieren
  if (!originalDoc?.readAt) {
    return {
      ...data,
      readAt: new Date().toISOString(),
      readBy: req.user.id,
      // Setze Status auf "gelesen" wenn noch "neu"
      status: originalDoc?.status === 'new' ? 'read' : (data.status || originalDoc?.status),
    }
  }

  return data
}

/**
 * Hook: Setzt Antwort-Zeitstempel automatisch
 */
export const setResponseTimestamp: CollectionBeforeChangeHook<FormSubmissionDoc> = async ({
  data,
  req,
  originalDoc,
}) => {
  // Prüfe ob "responded" gerade auf true gesetzt wurde
  const wasResponded = originalDoc?.responseTracking?.responded
  const isNowResponded = data?.responseTracking?.responded

  if (!wasResponded && isNowResponded && req.user) {
    return {
      ...data,
      responseTracking: {
        ...(data.responseTracking || {}),
        respondedAt: new Date().toISOString(),
        respondedBy: req.user.id,
      },
    }
  }

  return data
}

/**
 * Kombinierter BeforeChange Hook
 */
export const formSubmissionBeforeChange: CollectionBeforeChangeHook<FormSubmissionDoc> = async (
  args
) => {
  let data = args.data

  // Notiz-Metadaten setzen
  const result1 = await setNoteMetadata({ ...args, data })
  data = result1 as FormSubmissionDoc

  // Als gelesen markieren
  const result2 = await markAsRead({ ...args, data })
  data = result2 as FormSubmissionDoc

  // Antwort-Zeitstempel setzen
  const result3 = await setResponseTimestamp({ ...args, data })
  data = result3 as FormSubmissionDoc

  return data
}
