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

export const Users: CollectionConfig = {
  slug: 'users',
  admin: {
    useAsTitle: 'email',
  },
  labels: {
    singular: {
      de: "Benutzerkonto"
    },
    plural: {
      de: "Benutzerkonten"
    }
  },
  auth: {
    maxLoginAttempts: 10,
    lockTime: 1000 * 30
  },
  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: 'Gruppen (Bearbeitungsrechte)',
      },
      type: 'relationship',
      relationTo: 'group',
      hasMany: true,
      maxDepth: 0,
    },
    {
      name: 'parishes',
      label: {
        de: 'Gemeinden (Bearbeitungsrechte)',
      },
      type: 'relationship',
      relationTo: 'parish',
      hasMany: true,
      maxDepth: 0,
    },
    {
      name: 'pages',
      label: {
        de: 'Seiten (Bearbeitungsrechte)',
      },
      type: 'relationship',
      relationTo: 'pages',
      hasMany: true,
      maxDepth: 0,
    },
  ],
  access: {
    read: isAdminOrEmployee(),
    create: isAdminOrEmployee(),
    update: isAdminOrEmployee(),
    delete: isAdmin(),
  },
}
