import type { CollectionConfig } from 'payload'

import { anyone } from '../access/anyone'
import { authenticated } from '../access/authenticated'
import { slugField } from '@/fields/slug'

export const Papers: CollectionConfig = {
  slug: 'papers',
  labels: {
    singular: 'Diplomarbeit',
    plural: 'Diplomarbeiten',
  },
  access: {
    create: authenticated,
    delete: authenticated,
    read: anyone,
    update: authenticated,
  },
  admin: {
    useAsTitle: 'title',
  },
  fields: [
    {
      name: 'title',
      type: 'text',
      required: true,
    },
    {
      name: 'issue',
      label: 'Problemstellung',
      type: 'textarea',
      required: true,
    },
    {
      name: 'goal',
      label: 'Zielsetzung',
      type: 'textarea',
      required: true,
    },
    {
      name: 'technologies',
      type: 'array',
      fields: [
        {
          name: 'technology',
          type: 'relationship',
          relationTo: 'technologies',
          required: true,
        },
        {
          name: 'description',
          type: 'text',
          required: true,
          admin: {
            placeholder: '... wurde für das Frontend verwendet',
          }
        },
      ],
    },
    {
      name: 'prototype',
      type: 'group',
      fields: [
        {
          name: 'image',
          type: 'upload',
          relationTo: 'media',
          required: true,
        },
        {
          name: 'description',
          type: 'text',
          required: true,
        },
      ],
    },

    {
      name: 'authors',
      type: 'array',
      label: 'Projektmitglieder',
      required: true,
      fields: [
        {
          name: 'profilePicture',
          type: 'upload',
          relationTo: 'media',
          required: true,
        },
        {
          name: 'user',
          type: 'relationship',
          relationTo: 'users',
          required: true,
        },
        {
          name: 'position',
          type: 'select',
          required: true,
          options: [
            {
              label: 'Projektleiter (PL)',
              value: 'leader',
            },
            {
              label: 'Projektmitarbeiter (PM)',
              value: 'member',
            },
          ],
        },
        {
          name: 'description',
          type: 'text',
          required: true,
        },

      ],
      validate: (authors) => {
        const leaders = authors.filter(author => author.position === 'leader')
        if (leaders.length > 1) {
          return 'Only one author can be the project leader.'
        }
        return true
      },
    },
    ...slugField(),
  ],
}
