import type { CollectionConfig } from 'payload'
import { emailFailureAlertHook } from '../hooks/emailFailureAlertHook'
import { emailLogsAccess } from '../lib/access'

export const EmailLogs: CollectionConfig = {
  slug: 'email-logs',
  admin: {
    useAsTitle: 'subject',
    group: 'System',
    description: 'Protokoll aller gesendeten E-Mails',
    defaultColumns: ['to', 'subject', 'status', 'tenant', 'createdAt'],
  },
  hooks: {
    afterChange: [emailFailureAlertHook],
  },
  access: emailLogsAccess,
  fields: [
    {
      name: 'tenant',
      type: 'relationship',
      relationTo: 'tenants',
      required: true,
      label: 'Tenant',
      admin: {
        readOnly: true,
      },
    },
    {
      name: 'to',
      type: 'text',
      required: true,
      label: 'Empfänger',
      admin: {
        readOnly: true,
      },
    },
    {
      name: 'from',
      type: 'text',
      required: true,
      label: 'Absender',
      admin: {
        readOnly: true,
      },
    },
    {
      name: 'subject',
      type: 'text',
      required: true,
      label: 'Betreff',
      admin: {
        readOnly: true,
      },
    },
    {
      name: 'status',
      type: 'select',
      required: true,
      defaultValue: 'pending',
      options: [
        { label: 'Ausstehend', value: 'pending' },
        { label: 'Gesendet', value: 'sent' },
        { label: 'Fehlgeschlagen', value: 'failed' },
      ],
      admin: {
        readOnly: true,
      },
    },
    {
      name: 'messageId',
      type: 'text',
      label: 'Message-ID',
      admin: {
        readOnly: true,
        description: 'SMTP Message-ID bei erfolgreichem Versand',
      },
    },
    {
      name: 'error',
      type: 'textarea',
      label: 'Fehlermeldung',
      admin: {
        readOnly: true,
        condition: (data) => data?.status === 'failed',
      },
    },
    {
      name: 'source',
      type: 'select',
      required: true,
      defaultValue: 'manual',
      options: [
        { label: 'Manuell (API)', value: 'manual' },
        { label: 'Formular-Einsendung', value: 'form' },
        { label: 'System (Auth)', value: 'system' },
        { label: 'Newsletter', value: 'newsletter' },
      ],
      label: 'Quelle',
      admin: {
        readOnly: true,
      },
    },
    {
      name: 'metadata',
      type: 'json',
      label: 'Zusätzliche Daten',
      admin: {
        readOnly: true,
        description: 'Zusätzliche Kontextinformationen (z.B. Form-ID)',
      },
    },
  ],
}
