import type { CollectionConfig } from 'payload'
import { authenticatedOnly, tenantScopedPublicRead } from '../lib/tenantAccess'

/**
 * Downloads Collection
 *
 * Downloadbare Dateien wie PDFs, Broschüren, Formulare, etc.
 * Mit Kategorisierung, Tracking und Zugriffskontrolle.
 */
export const Downloads: CollectionConfig = {
  slug: 'downloads',
  labels: {
    singular: 'Download',
    plural: 'Downloads',
  },
  admin: {
    useAsTitle: 'title',
    group: 'Content',
    defaultColumns: ['title', 'category', 'fileType', 'downloadCount', 'isActive'],
    description: 'Downloadbare Dateien und Dokumente',
  },
  access: {
    read: tenantScopedPublicRead,
    create: authenticatedOnly,
    update: authenticatedOnly,
    delete: authenticatedOnly,
  },
  fields: [
    {
      name: 'title',
      type: 'text',
      required: true,
      label: 'Titel',
      localized: true,
    },
    {
      name: 'slug',
      type: 'text',
      required: true,
      unique: true,
      label: 'Slug',
    },
    {
      name: 'description',
      type: 'textarea',
      label: 'Beschreibung',
      localized: true,
    },
    {
      name: 'file',
      type: 'upload',
      relationTo: 'media',
      required: true,
      label: 'Datei',
    },
    {
      name: 'fileType',
      type: 'select',
      label: 'Dateityp',
      options: [
        { label: 'PDF', value: 'pdf' },
        { label: 'Word', value: 'doc' },
        { label: 'Excel', value: 'xls' },
        { label: 'PowerPoint', value: 'ppt' },
        { label: 'Bild', value: 'image' },
        { label: 'Video', value: 'video' },
        { label: 'Audio', value: 'audio' },
        { label: 'ZIP/Archiv', value: 'archive' },
        { label: 'Sonstiges', value: 'other' },
      ],
      admin: {
        position: 'sidebar',
        description: 'Wird automatisch erkannt, kann überschrieben werden',
      },
    },
    {
      name: 'fileSize',
      type: 'text',
      label: 'Dateigröße',
      admin: {
        position: 'sidebar',
        description: 'z.B. "2.5 MB" - wird automatisch berechnet',
        readOnly: true,
      },
    },
    // Kategorisierung
    {
      name: 'category',
      type: 'select',
      label: 'Kategorie',
      options: [
        { label: 'Broschüre', value: 'brochure' },
        { label: 'Flyer', value: 'flyer' },
        { label: 'Katalog', value: 'catalog' },
        { label: 'Preisliste', value: 'pricelist' },
        { label: 'Formular', value: 'form' },
        { label: 'Anleitung', value: 'manual' },
        { label: 'Datenblatt', value: 'datasheet' },
        { label: 'Zertifikat', value: 'certificate' },
        { label: 'Pressematerial', value: 'press' },
        { label: 'Whitepaper', value: 'whitepaper' },
        { label: 'Präsentation', value: 'presentation' },
        { label: 'Vertrag/AGB', value: 'legal' },
        { label: 'Sonstiges', value: 'other' },
      ],
    },
    {
      name: 'tags',
      type: 'array',
      label: 'Tags',
      fields: [
        {
          name: 'tag',
          type: 'text',
          required: true,
        },
      ],
    },
    // Vorschau
    {
      name: 'thumbnail',
      type: 'upload',
      relationTo: 'media',
      label: 'Vorschaubild',
      admin: {
        description: 'Optionales Thumbnail (sonst wird Standard-Icon verwendet)',
      },
    },
    // Verknüpfungen
    {
      name: 'relatedServices',
      type: 'relationship',
      relationTo: 'services',
      hasMany: true,
      label: 'Zugehörige Services',
    },
    {
      name: 'relatedProducts',
      type: 'relationship',
      relationTo: 'products',
      hasMany: true,
      label: 'Zugehörige Produkte',
    },
    // Zugriff
    {
      name: 'access',
      type: 'group',
      label: 'Zugriff',
      fields: [
        {
          name: 'requireLogin',
          type: 'checkbox',
          defaultValue: false,
          label: 'Login erforderlich',
        },
        {
          name: 'requireForm',
          type: 'checkbox',
          defaultValue: false,
          label: 'Formular vor Download',
          admin: {
            description: 'User müssen Kontaktdaten eingeben',
          },
        },
        {
          name: 'formFields',
          type: 'select',
          hasMany: true,
          label: 'Formular-Felder',
          options: [
            { label: 'Name', value: 'name' },
            { label: 'E-Mail', value: 'email' },
            { label: 'Firma', value: 'company' },
            { label: 'Telefon', value: 'phone' },
          ],
          admin: {
            condition: (_, siblingData) => siblingData?.requireForm,
          },
        },
      ],
    },
    // Tracking
    {
      name: 'downloadCount',
      type: 'number',
      defaultValue: 0,
      label: 'Downloads',
      admin: {
        position: 'sidebar',
        readOnly: true,
      },
    },
    // Version
    {
      name: 'version',
      type: 'text',
      label: 'Version',
      admin: {
        description: 'z.B. "2024-01", "v2.0"',
      },
    },
    {
      name: 'lastUpdated',
      type: 'date',
      label: 'Letzte Aktualisierung',
    },
    // Status
    {
      name: 'isActive',
      type: 'checkbox',
      defaultValue: true,
      label: 'Aktiv',
      admin: {
        position: 'sidebar',
      },
    },
    {
      name: 'isFeatured',
      type: 'checkbox',
      defaultValue: false,
      label: 'Hervorgehoben',
      admin: {
        position: 'sidebar',
      },
    },
    {
      name: 'order',
      type: 'number',
      defaultValue: 0,
      label: 'Sortierung',
      admin: {
        position: 'sidebar',
      },
    },
  ],
  hooks: {
    beforeChange: [
      ({ data }) => {
        if (data && !data.slug && data.title) {
          const titleStr = typeof data.title === 'string' ? data.title : ''
          data.slug = titleStr
            .toLowerCase()
            .replace(/[äöüß]/g, (match: string) => {
              const map: Record<string, string> = { ä: 'ae', ö: 'oe', ü: 'ue', ß: 'ss' }
              return map[match] || match
            })
            .replace(/[^a-z0-9]+/g, '-')
            .replace(/^-|-$/g, '')
        }
        return data
      },
    ],
  },
}
