import type { CollectionConfig } from 'payload'

/**
 * Tags Collection
 *
 * Schlagwörter für Blog-Posts und andere Inhalte.
 * Flexibler als Kategorien, für freie Verschlagwortung.
 */
export const Tags: CollectionConfig = {
  slug: 'tags',
  labels: {
    singular: 'Tag',
    plural: 'Tags',
  },
  admin: {
    useAsTitle: 'name',
    group: 'Content',
    defaultColumns: ['name', 'slug', 'postCount', 'updatedAt'],
    description: 'Schlagwörter für Blog-Posts',
  },
  access: {
    read: () => true,
    create: ({ req }) => !!req.user,
    update: ({ req }) => !!req.user,
    delete: ({ req }) => !!req.user,
  },
  fields: [
    {
      name: 'name',
      type: 'text',
      required: true,
      localized: true,
      label: 'Name',
    },
    {
      name: 'slug',
      type: 'text',
      required: true,
      unique: true,
      label: 'Slug',
      admin: {
        description: 'URL-freundlicher Identifier (z.B. "javascript")',
      },
    },
    {
      name: 'description',
      type: 'textarea',
      localized: true,
      label: 'Beschreibung',
      admin: {
        description: 'Optionale Beschreibung für Tag-Archivseiten',
      },
    },
    {
      name: 'color',
      type: 'text',
      label: 'Farbe',
      admin: {
        description: 'Optionale Farbe für Tag-Badge (z.B. "#3B82F6" oder "blue")',
      },
    },
  ],
  hooks: {
    beforeChange: [
      ({ data }) => {
        // Auto-generate slug from name if not provided
        if (data && !data.slug && data.name) {
          data.slug = data.name
            .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
      },
    ],
  },
}
