import { CollectionConfig } from 'payload'
import { isAdminOrEmployee } from '@/collections/access/admin'
import { canMutateOccurrenceOfAssignedEvent } from '@/collections/access/assigned'
import { revalidateTagHook } from '@/utils/revalidate'

export const EventOccurrences: CollectionConfig = {
  slug: 'eventOccurrence',
  labels: {
    singular: {
      de: 'Veranstaltungs-Termin',
    },
    plural: {
      de: 'Veranstaltungs-Termine',
    },
  },
  fields: [
    {
      name: 'event',
      type: 'relationship',
      relationTo: 'event',
      required: true,
      index: true,
      label: {
        de: 'Veranstaltung',
      },
    },
    {
      name: 'date',
      type: 'date',
      required: true,
      index: true,
      label: {
        de: 'Datum',
      },
      admin: {
        date: {
          pickerAppearance: 'dayAndTime',
          timeIntervals: 15,
          timeFormat: 'HH:mm',
        },
      },
    },
    {
      name: 'endDateTime',
      type: 'date',
      index: true,
      label: {
        de: 'Enduhrzeit',
      },
      admin: {
        date: {
          pickerAppearance: 'dayAndTime',
          timeIntervals: 15,
          timeFormat: 'HH:mm',
        },
      },
    },
    {
      name: 'cancelled',
      type: 'checkbox',
      required: true,
      defaultValue: false,
      label: {
        de: 'Abgesagt',
      },
      admin: {
        position: 'sidebar',
      },
    },
    {
      name: 'generated',
      type: 'checkbox',
      defaultValue: false,
      label: {
        de: 'Automatisch erzeugt',
      },
      admin: {
        readOnly: true,
        position: 'sidebar',
      },
    },
  ],
  admin: {
    defaultColumns: ['date', 'event', 'cancelled'],
    hidden: true,
  },
  access: {
    read: () => true,
    create: isAdminOrEmployee(),
    // Whoever may edit the parent event may cancel/uncancel its occurrences
    // (used by the "Nächste Termine" table on the event edit view).
    update: canMutateOccurrenceOfAssignedEvent(),
    delete: isAdminOrEmployee(),
  },
  hooks: {
    afterChange: [revalidateTagHook('events')],
    afterDelete: [revalidateTagHook('events')],
  },
}
