import type { CollectionConfig } from 'payload'
import { lexicalEditor } from '@payloadcms/richtext-lexical'
import slugify from 'slugify'

export const Neuigkeiten: CollectionConfig = {
    labels: {
        singular: 'Beitrag',
        plural: 'Beiträge',
    },
    slug: 'neuigkeiten',
    admin: {
        useAsTitle: 'title',
        defaultColumns: ['title', 'author', 'publishedAt', '_status'],
        description: 'Nachrichtenartikel und Beiträge',
    },
    // Draft/publish workflow
    versions: {
        drafts: {
            autosave: {
                interval: 2000,
            },
        },
    },
    // Restrict writes to logged-in users, reads are public
    access: {
        read:   () => true,
        create: ({ req }) => ['admin', 'editor', 'author'].includes(req.user?.role ?? ''),
        update: ({ req }) => ['admin', 'editor', 'author'].includes(req.user?.role ?? ''),
        delete: ({ req }) => ['admin', 'editor'].includes(req.user?.role ?? ''),
    },
    hooks: {
        beforeValidate: [
            ({ data, req }) => {
                if (!data) return data
                const locale = req.locale || 'de'
                const title = typeof data.title === 'object' ? data.title?.[locale] : data.title

                if (title && !data?.slug) {
                    const raw = slugify(title as string, {
                        lower: true,
                        strict: true,
                        locale,
                    })
                    // Strip any JSON wrapper if slugify somehow returns {"xx":"..."}
                    data.slug = raw.replace(/^\{.*?"([^"]+)"\}$/, '$1')
                }
                return data
            }
        ]
    },
    fields: [
        {
            name: 'title',
            type: 'text',
            required: true,
            localized: true,
        },
        {
            name: 'slug',
            type: 'text',
            localized: true,
            unique: true,
            index: true,
            admin: {
                position: 'sidebar',
                description: 'Wird automatisch generiert — nur bei Bedarf manuell anpassen.',
            },
        },
        {
            name: 'excerpt',
            type: 'textarea',
            localized: true,
            admin: {
                description: 'Kurze Zusammenfassung für Listenansichten.',
            },
        },
        {
            name: 'featuredImage',
            type: 'upload',
            relationTo: 'media',
            admin: {
                position: 'sidebar',
            },
        },
        {
            name: 'author',
            type: 'relationship',
            relationTo: 'users',
            required: true,
            admin: {
                position: 'sidebar',
            },
            hooks: {
                beforeChange: [
                    ({ value, siblingData, req }) => {
                        // Auto-assign author on create
                        if (!value && req.user) return req.user.id
                        return value
                    },
                ],
            },
        },
        {
            name: 'tags',
            label: 'Schlagwörter',
            type: 'array',
            admin: {
                description: 'Thematische Schlagwörter für die Filterung, z.B. "Siedlungsgeschichte", "Pécs".',
            },
            fields: [
                {
                    name: 'tag',
                    label: 'Schlagwort',
                    type: 'text',
                    required: true,
                },
            ],
        },
        {
            name: 'publishedAt',
            type: 'date',
            admin: {
                position: 'sidebar',
                date: {
                    pickerAppearance: 'dayAndTime',
                },
                description: 'Leer lassen für sofortige Veröffentlichung.',
            },
            hooks: {
                beforeChange: [
                    ({ value, siblingData }) => {
                        // Auto-set publishedAt when status changes to published
                        if (!value && siblingData?._status === 'published') {
                            return new Date().toISOString()
                        }
                        return value
                    },
                ],
            },
        },
        {
            name: 'content',
            type: 'richText',
            required: true,
            localized: true,
            editor: lexicalEditor({
                features: ({ defaultFeatures }) => defaultFeatures,
            }),
        },
        // Auto-generated SEO — writers don't touch this
        {
            name: 'meta',
            type: 'group',
            admin: {
                description: 'Wird automatisch befüllt — kein manueller Aufwand nötig.',
            },
            fields: [
                {
                    name: 'title',
                    type: 'text',
                    localized: true,
                    admin: { readOnly: true },
                },
                {
                    name: 'description',
                    type: 'textarea',
                    localized: true,
                    admin: { readOnly: true },
                },
            ],
        },
    ],
}