import type { CollectionConfig } from 'payload'
import { isSuperAdmin } from '@/access/isSuperAdmin'
import { hasTenantRole } from '@/access/roles'

/**
 * Residents Collection
 *
 * Stores permanent resident information for each care home.
 * Multi-tenant: each resident belongs to a specific care home (tenant).
 */
export const Residents: CollectionConfig = {
  slug: 'residents',
  labels: {
    singular: 'Resident',
    plural: 'Residents',
  },
  admin: {
    useAsTitle: 'name',
    description: 'Manage residents in your care home',
    defaultColumns: ['name', 'room', 'station', 'table', 'active'],
    group: 'Meal Planning',
  },
  access: {
    // Only super-admin and tenant admin can create residents
    create: ({ req }) => {
      if (!req.user) return false
      if (isSuperAdmin(req.user)) return true
      return hasTenantRole(req.user, 'admin')
    },
    // All authenticated users within the tenant can read residents
    read: ({ req }) => {
      if (!req.user) return false
      return true // Multi-tenant plugin will filter by tenant
    },
    // Only super-admin and tenant admin can update residents
    update: ({ req }) => {
      if (!req.user) return false
      if (isSuperAdmin(req.user)) return true
      return hasTenantRole(req.user, 'admin')
    },
    // Only super-admin and tenant admin can delete residents
    delete: ({ req }) => {
      if (!req.user) return false
      if (isSuperAdmin(req.user)) return true
      return hasTenantRole(req.user, 'admin')
    },
  },
  fields: [
    {
      name: 'name',
      type: 'text',
      required: true,
      admin: {
        description: 'Full name of the resident',
      },
    },
    {
      name: 'room',
      type: 'text',
      required: true,
      index: true,
      admin: {
        description: 'Room number (Zimmer)',
      },
    },
    {
      name: 'table',
      type: 'text',
      admin: {
        description: 'Table assignment in dining area (Tisch)',
      },
    },
    {
      name: 'station',
      type: 'text',
      admin: {
        description: 'Station or ward',
      },
    },
    {
      type: 'row',
      fields: [
        {
          name: 'highCaloric',
          type: 'checkbox',
          defaultValue: false,
          admin: {
            description: 'Requires high-caloric meals (Hochkalorisch)',
            width: '50%',
          },
        },
        {
          name: 'active',
          type: 'checkbox',
          defaultValue: true,
          admin: {
            description: 'Is the resident currently active?',
            width: '50%',
          },
        },
      ],
    },
    {
      name: 'aversions',
      type: 'textarea',
      admin: {
        description: 'Food aversions and dislikes (Abneigungen)',
      },
    },
    {
      name: 'notes',
      type: 'textarea',
      admin: {
        description: 'Other notes and special requirements (Sonstiges)',
      },
    },
  ],
}
