import { CollectionConfig } from 'payload'
import { nextSunday } from '@/utils/sunday'
import {
  canCreateAssignedAnnouncement,
  canMutateAssignedAnnouncement,
  defaultToOnlyAssigned,
  filterAnnouncementsToAssigned,
  hideUnlessAssigned,
  unassignedAdditions,
} from '@/collections/access/assigned'

export const Announcements: CollectionConfig = {
  slug: 'announcement',
  labels: {
    singular: {
      de: 'Vermeldung'
    },
    plural: {
      de: 'Vermeldungen'
    }
  },
  fields: [
    {
      name: 'date',
      type: 'date',
      required: true,
      label: {
        de: 'Datum'
      },
      defaultValue: nextSunday()
    },
    {
      name: 'parish',
      type: "relationship",
      relationTo: 'parish',
      required: true,
      hasMany: true,
      label: {
        de: "Gemeinde"
      },
      admin: {
        allowCreate: false,
        allowEdit: false
      },
      defaultValue: defaultToOnlyAssigned('parishes'),
      // A Gläubiger may only add parishes assigned to them; connections
      // already on the doc (set by staff) may always be kept.
      validate: (value: unknown, options: any) => {
        // A custom validate replaces the built-in one, so re-assert `required`.
        if (!Array.isArray(value) || value.length === 0) {
          return 'Dieses Feld ist erforderlich.'
        }
        const user = options.req?.user
        if (!user || user.roles !== 'user') return true
        if (unassignedAdditions(user, 'parishes', value, options.previousValue).length > 0) {
          return 'Sie können nur Gemeinden hinzufügen, die Ihnen zugewiesen sind.'
        }
        return true
      }
    },
    {
      name: 'document',
      label: {
        de: "PDF-Dokument"
      },
      type: 'upload',
      relationTo: 'documents',
      required: true
    }
  ],
  admin: {
    hidden: hideUnlessAssigned('parishes'),
    baseFilter: filterAnnouncementsToAssigned(),
    description: 'Die Vermeldungen werden jeden Samstag automatisch veröffentlicht.',
    defaultColumns: ['date', 'parish', 'document']
  },
  access: {
    read: () => true,
    create: canCreateAssignedAnnouncement(),
    update: canMutateAssignedAnnouncement(),
    delete: canMutateAssignedAnnouncement(),
  }
}