import { CollectionConfig } from 'payload'
import { isAdminOrEmployee } from '@/collections/access/admin'

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: 'description',
      type: 'textarea',
      label: {
        de: 'Umschreibung',
      },
      required: 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(),
  },
}
