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

export const Users: CollectionConfig = {
  slug: 'users',
  admin: {
    useAsTitle: 'email',
  },
  auth: true,
  fields: [
    {
      name: 'name',
      label: {
        de: 'Name',
      },
      type: 'text',
      required: true,
      defaultValue: '',
    },
    {
      name: 'roles',
      label: {
        de: 'Rolle',
      },
      type: 'select',
      required: true,
      options: [
        {
          value: 'user',
          label: 'Gläubiger',
        },
        {
          value: 'employee',
          label: 'Mitarbeiter',
        },
        {
          value: 'admin',
          label: 'Administrator',
        },
      ],
      defaultValue: 'user',
      access: {
        // Do not allow to upgrade role
        create: ({ req, data }) => {
          return !(req.user?.roles !== 'admin' && data?.roles === 'admin')
        },
        update: ({ req, data }) => {
          return !(req.user?.roles !== 'admin' && data?.roles === 'admin')
        },
      },
    },
    {
      name: 'groups',
      label: {
        de: 'Mitgliedschaft',
      },
      type: 'relationship',
      relationTo: 'group',
      hasMany: true,
      maxDepth: 0,
    },
  ],
  access: {
    create: isAdminOrEmployee(),
    update: isAdminOrEmployee(),
    delete: isAdminOrEmployee(),
  },
}
