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

/**
 * Media Collection
 *
 * Stores uploaded files (images) for meal order forms.
 * Used by caregivers to upload photos of paper meal order forms.
 */
export const Media: CollectionConfig = {
  slug: 'media',
  labels: {
    singular: 'Media',
    plural: 'Media',
  },
  admin: {
    description: 'Uploaded images and files',
    group: 'System',
  },
  access: {
    // Admin and caregiver can upload
    create: ({ req }) => {
      if (!req.user) return false
      if (isSuperAdmin(req.user)) return true
      return hasTenantRole(req.user, 'admin') || hasTenantRole(req.user, 'caregiver')
    },
    // All authenticated users can read
    read: ({ req }) => {
      if (!req.user) return false
      return true
    },
    // Admin and caregiver can update
    update: ({ req }) => {
      if (!req.user) return false
      if (isSuperAdmin(req.user)) return true
      return hasTenantRole(req.user, 'admin') || hasTenantRole(req.user, 'caregiver')
    },
    // Only admin can delete
    delete: ({ req }) => {
      if (!req.user) return false
      if (isSuperAdmin(req.user)) return true
      return hasTenantRole(req.user, 'admin')
    },
  },
  upload: {
    staticDir: 'media',
    mimeTypes: ['image/*'],
    imageSizes: [
      {
        name: 'thumbnail',
        width: 200,
        height: 200,
        position: 'centre',
      },
      {
        name: 'preview',
        width: 800,
        height: 800,
        position: 'centre',
      },
    ],
  },
  fields: [
    {
      name: 'alt',
      type: 'text',
      admin: {
        description: 'Alternative text for accessibility',
      },
    },
    {
      name: 'caption',
      type: 'text',
      admin: {
        description: 'Optional caption for the image',
      },
    },
  ],
}
