import { CollectionConfig } from 'payload'
import { isAdminOrEmployee } from '@/collections/access/admin'
import { ParagraphBlock } from '@/collections/blocks/Paragraph'
import { GalleryBlock } from '@/collections/blocks/Gallery'
import { ContactformBlock } from '@/collections/blocks/Contactform'
import { DocumentBlock } from '@/collections/blocks/Document'
import { lexicalHTML } from '@payloadcms/richtext-lexical'

export const Groups: CollectionConfig = {
  slug: 'group',
  labels: {
    singular: {
      de: 'Gruppe',
    },
    plural: {
      de: 'Gruppen',
    },
  },
  fields: [
    {
      name: 'photo',
      label: {
        de: 'Foto',
      },
      type: 'upload',
      relationTo: 'media',
    },
    {
      name: 'name',
      type: 'text',
      label: {
        de: 'Name',
      },
      required: true,
    },
    {
      name: 'slug',
      type: 'text',
      label: {
        de: 'URL slug',
      },
      required: true,
      unique: true
    },
    {
      name: 'shortDescription',
      type: 'textarea',
      label: {
        de: 'Kurzumschreibung',
      },
      required: true,
    },
    {
      name: 'text',
      type: 'richText',
      label: {
        de: 'Umschreibung',
      },
      required: false,
    },
    lexicalHTML('text', { name: 'text_html' }),
    {
      name: 'content',
      type: 'blocks',
      blocks: [
        ParagraphBlock,
        GalleryBlock,
        DocumentBlock,
        ContactformBlock
      ]
    }
  ],
  defaultPopulate: {
    slug: true
  },
  admin: {
    useAsTitle: 'name',
  },
  access: {
    read: () => true,
    create: isAdminOrEmployee(),
    update: ({ req, id }) => {
      if (!req.user) {
        return false
      }

      if (
        req.user.roles === 'user' &&
        id &&
        req.user.groups?.find(
          (group) =>
            group === id || (typeof group === 'object' && group.id === id),
        ) === undefined
      ) {
        return false
      }

      return true
    },
    delete: isAdminOrEmployee(),
  },
}
