// src/collections/NewsletterSubscribers.ts

import type { CollectionConfig } from 'payload'
import { authenticatedOnly } from '../lib/tenantAccess'
import { sendNewsletterConfirmation } from '../hooks/sendNewsletterConfirmation'

/**
 * Newsletter Subscribers Collection
 *
 * DSGVO-konforme Speicherung von Newsletter-Anmeldungen.
 * Öffentlich schreibbar (Anmeldung), nur für Admins lesbar.
 */
export const NewsletterSubscribers: CollectionConfig = {
  slug: 'newsletter-subscribers',
  admin: {
    useAsTitle: 'email',
    group: 'Marketing',
    defaultColumns: ['email', 'status', 'source', 'subscribedAt'],
    description: 'Newsletter-Abonnenten (DSGVO-konform)',
  },
  access: {
    // Nur Admins können Subscribers lesen (Datenschutz)
    read: authenticatedOnly,
    // Öffentlich subscriben möglich
    create: () => true,
    update: authenticatedOnly,
    delete: authenticatedOnly,
  },
  fields: [
    {
      name: 'email',
      type: 'email',
      required: true,
      label: 'E-Mail-Adresse',
    },
    {
      name: 'firstName',
      type: 'text',
      label: 'Vorname',
    },
    {
      name: 'lastName',
      type: 'text',
      label: 'Nachname',
    },
    {
      name: 'status',
      type: 'select',
      required: true,
      defaultValue: 'pending',
      options: [
        { label: 'Ausstehend (Double Opt-In)', value: 'pending' },
        { label: 'Bestätigt', value: 'confirmed' },
        { label: 'Abgemeldet', value: 'unsubscribed' },
        { label: 'Bounced', value: 'bounced' },
      ],
      admin: {
        position: 'sidebar',
      },
    },
    {
      name: 'interests',
      type: 'select',
      hasMany: true,
      label: 'Interessen',
      options: [
        { label: 'Allgemeine Updates', value: 'general' },
        { label: 'Blog-Artikel', value: 'blog' },
        { label: 'Produkt-News', value: 'products' },
        { label: 'Angebote & Aktionen', value: 'offers' },
        { label: 'Events', value: 'events' },
      ],
    },
    {
      name: 'source',
      type: 'text',
      label: 'Anmeldequelle',
      admin: {
        description: 'z.B. "Footer", "Popup", "Blog-Artikel", "Kontakt-Seite"',
      },
    },
    {
      name: 'subscribedAt',
      type: 'date',
      label: 'Anmeldedatum',
      admin: {
        readOnly: true,
        date: { pickerAppearance: 'dayAndTime' },
      },
    },
    {
      name: 'confirmedAt',
      type: 'date',
      label: 'Bestätigungsdatum',
      admin: {
        readOnly: true,
        date: { pickerAppearance: 'dayAndTime' },
      },
    },
    {
      name: 'unsubscribedAt',
      type: 'date',
      label: 'Abmeldedatum',
      admin: {
        readOnly: true,
        date: { pickerAppearance: 'dayAndTime' },
      },
    },
    {
      name: 'confirmationToken',
      type: 'text',
      label: 'Bestätigungs-Token',
      admin: {
        readOnly: true,
        hidden: true,
      },
    },
    {
      name: 'ipAddress',
      type: 'text',
      label: 'IP-Adresse',
      admin: {
        readOnly: true,
        description: 'DSGVO-Nachweis der Anmeldung',
      },
    },
    {
      name: 'userAgent',
      type: 'text',
      label: 'User Agent',
      admin: {
        readOnly: true,
        hidden: true,
      },
    },
  ],
  hooks: {
    beforeChange: [
      ({ data, operation }) => {
        // Automatisch Timestamps setzen
        if (operation === 'create') {
          data.subscribedAt = new Date().toISOString()
          // Zufälliges Token für Double Opt-In
          data.confirmationToken = crypto.randomUUID()
        }

        // Status-Änderungen tracken
        if (data.status === 'confirmed' && !data.confirmedAt) {
          data.confirmedAt = new Date().toISOString()
        }
        if (data.status === 'unsubscribed' && !data.unsubscribedAt) {
          data.unsubscribedAt = new Date().toISOString()
        }

        return data
      },
    ],
    afterChange: [
      // Sendet automatisch Double Opt-In E-Mail bei neuen Anmeldungen
      sendNewsletterConfirmation,
    ],
  },
}
