import type { CollectionBeforeValidateHook } from 'payload'

/**
 * Hook to auto-generate the title field from date, meal type, and resident name
 * Format: "Breakfast - 2024-01-15 - John Doe"
 */
export const generateTitle: CollectionBeforeValidateHook = async ({ data, req, operation: _operation }) => {
  if (!data) return data

  const mealType = data.mealType
  const date = data.date

  // Format meal type with first letter capitalized
  const mealTypeLabel =
    mealType === 'breakfast' ? 'Breakfast' : mealType === 'lunch' ? 'Lunch' : 'Dinner'

  // Format date as YYYY-MM-DD
  let dateStr = ''
  if (date) {
    const dateObj = typeof date === 'string' ? new Date(date) : date
    dateStr = dateObj.toISOString().split('T')[0]
  }

  // Get resident name if we have the resident ID
  let residentName = ''
  if (data.resident && req.payload) {
    try {
      const residentId = typeof data.resident === 'object' ? data.resident.id : data.resident
      if (residentId) {
        const resident = await req.payload.findByID({
          collection: 'residents',
          id: residentId,
          depth: 0,
        })
        if (resident?.name) {
          residentName = resident.name
        }
      }
    } catch {
      // If we can't fetch the resident, just skip the name
    }
  }

  // Compose title
  const parts = [mealTypeLabel, dateStr, residentName].filter(Boolean)
  const title = parts.join(' - ')

  return {
    ...data,
    title: title || 'New Meal Order',
  }
}
