import type { Payload } from 'payload'
import { formatISO } from 'date-fns'

/**
 * Seed script for the Meal Planner application
 *
 * Creates:
 * - 1 care home (tenant)
 * - 3 users (admin, caregiver, kitchen)
 * - 8 residents with varied data
 * - Meal orders with individual meals
 */
export const seed = async (payload: Payload): Promise<void> => {
  // Check if already seeded
  const existingResidents = await payload.find({
    collection: 'residents',
    limit: 1,
  })

  if (existingResidents.totalDocs > 0) {
    payload.logger.info('Database already seeded, skipping...')
    return
  }

  payload.logger.info('Seeding database...')

  // ============================================
  // CREATE CARE HOME (TENANT)
  // ============================================
  const careHome = await payload.create({
    collection: 'tenants',
    data: {
      name: 'Sunny Meadows Care Home',
      slug: 'sunny-meadows',
      domain: 'sunny-meadows.localhost',
      address: 'Sonnenweg 123\n12345 Musterstadt\nGermany',
      phone: '+49 123 456 7890',
    },
  })

  payload.logger.info(`Created care home: ${careHome.name}`)

  // ============================================
  // CREATE USERS
  // ============================================

  // Super Admin (can access all care homes)
  await payload.create({
    collection: 'users',
    data: {
      email: 'admin@example.com',
      password: 'test',
      name: 'System Administrator',
      roles: ['super-admin'],
    },
  })
  payload.logger.info('Created admin user: admin@example.com')

  // Caregiver (can create meal orders)
  const caregiver = await payload.create({
    collection: 'users',
    data: {
      email: 'caregiver@example.com',
      password: 'test',
      name: 'Maria Schmidt',
      roles: ['user'],
      tenants: [
        {
          tenant: careHome.id,
          roles: ['caregiver'],
        },
      ],
    },
  })
  payload.logger.info('Created caregiver user: caregiver@example.com')

  // Kitchen Staff (can view orders and mark as prepared)
  await payload.create({
    collection: 'users',
    data: {
      email: 'kitchen@example.com',
      password: 'test',
      name: 'Hans Weber',
      roles: ['user'],
      tenants: [
        {
          tenant: careHome.id,
          roles: ['kitchen'],
        },
      ],
    },
  })
  payload.logger.info('Created kitchen user: kitchen@example.com')

  // ============================================
  // CREATE RESIDENTS
  // ============================================
  const residentsData = [
    {
      name: 'Hans Mueller',
      room: '101',
      table: '1',
      station: 'Station A',
      highCaloric: false,
      aversions: '',
      notes: '',
    },
    {
      name: 'Ingrid Schmidt',
      room: '102',
      table: '1',
      station: 'Station A',
      highCaloric: true,
      aversions: 'Keine Nüsse (no nuts)',
      notes: 'Prefers soft foods',
    },
    {
      name: 'Wilhelm Bauer',
      room: '103',
      table: '2',
      station: 'Station A',
      highCaloric: false,
      aversions: 'Kein Fisch (no fish)',
      notes: '',
    },
    {
      name: 'Gertrude Fischer',
      room: '104',
      table: '2',
      station: 'Station A',
      highCaloric: false,
      aversions: '',
      notes: 'Diabetic - use sugar-free options',
    },
    {
      name: 'Karl Hoffmann',
      room: '105',
      table: '3',
      station: 'Station B',
      highCaloric: true,
      aversions: 'Keine Milchprodukte (no dairy)',
      notes: 'Lactose intolerant',
    },
    {
      name: 'Elisabeth Schulz',
      room: '106',
      table: '3',
      station: 'Station B',
      highCaloric: false,
      aversions: '',
      notes: '',
    },
    {
      name: 'Friedrich Wagner',
      room: '107',
      table: '4',
      station: 'Station B',
      highCaloric: false,
      aversions: 'Kein Schweinefleisch (no pork)',
      notes: '',
    },
    {
      name: 'Helga Meyer',
      room: '108',
      table: '4',
      station: 'Station B',
      highCaloric: true,
      aversions: '',
      notes: 'Requires pureed food',
    },
  ]

  const residents: Array<{ id: number; name: string }> = []
  for (const residentData of residentsData) {
    const resident = await payload.create({
      collection: 'residents',
      data: {
        ...residentData,
        active: true,
        tenant: careHome.id,
      },
    })
    residents.push({ id: resident.id, name: resident.name })
  }

  payload.logger.info(`Created ${residents.length} residents`)

  // ============================================
  // CREATE MEAL ORDERS AND MEALS
  // ============================================
  const today = new Date()
  const yesterday = new Date(today)
  yesterday.setDate(yesterday.getDate() - 1)
  const tomorrow = new Date(today)
  tomorrow.setDate(tomorrow.getDate() + 1)

  const formatDate = (date: Date) => date.toISOString().split('T')[0]

  type MealType = 'breakfast' | 'lunch' | 'dinner'
  type OrderStatus = 'draft' | 'submitted' | 'preparing' | 'completed'

  const mealOrders: Array<{
    date: string
    mealType: MealType
    status: OrderStatus
  }> = [
    // Yesterday - all completed
    { date: formatDate(yesterday), mealType: 'breakfast', status: 'completed' },
    { date: formatDate(yesterday), mealType: 'lunch', status: 'completed' },
    { date: formatDate(yesterday), mealType: 'dinner', status: 'completed' },
    // Today - mixed statuses
    { date: formatDate(today), mealType: 'breakfast', status: 'completed' },
    { date: formatDate(today), mealType: 'lunch', status: 'preparing' },
    { date: formatDate(today), mealType: 'dinner', status: 'submitted' },
    // Tomorrow - draft (in progress)
    { date: formatDate(tomorrow), mealType: 'breakfast', status: 'draft' },
    { date: formatDate(tomorrow), mealType: 'lunch', status: 'draft' },
  ]

  let totalMeals = 0

  for (const orderData of mealOrders) {
    // Create the meal order
    const order = await payload.create({
      collection: 'meal-orders',
      data: {
        date: orderData.date,
        mealType: orderData.mealType,
        status: orderData.status,
        createdBy: caregiver.id,
        tenant: careHome.id,
        submittedAt: orderData.status !== 'draft' ? formatISO(new Date()) : undefined,
      },
    })

    // Determine meal status based on order status
    const mealStatus =
      orderData.status === 'completed'
        ? 'prepared'
        : orderData.status === 'preparing'
          ? 'preparing'
          : 'pending'

    // Create meals for each resident in the order
    // For draft orders, only add some residents to demonstrate partial completion
    const residentsToUse =
      orderData.status === 'draft'
        ? residents.slice(0, Math.floor(residents.length / 2))
        : residents

    for (let i = 0; i < residentsToUse.length; i++) {
      const resident = residentsToUse[i]

      // eslint-disable-next-line @typescript-eslint/no-explicit-any
      const mealData: any = {
        order: order.id,
        resident: resident.id,
        date: orderData.date,
        mealType: orderData.mealType,
        status: mealStatus,
        createdBy: caregiver.id,
        tenant: careHome.id,
      }

      // Add meal-specific options based on meal type
      if (orderData.mealType === 'breakfast') {
        mealData.breakfast = {
          accordingToPlan: i % 3 === 0,
          bread: {
            breadRoll: i % 2 === 0,
            wholeGrainRoll: i % 3 === 0,
            greyBread: i % 4 === 0,
            wholeGrainBread: i % 5 === 0,
            whiteBread: false,
            crispbread: i % 6 === 0,
          },
          porridge: i % 4 === 0,
          preparation: {
            sliced: i % 2 === 0,
            spread: i % 2 === 1,
          },
          spreads: {
            butter: true,
            margarine: false,
            jam: i % 2 === 0,
            diabeticJam: i === 3,
            honey: i % 4 === 0,
            cheese: i % 3 === 0,
            quark: i % 5 === 0,
            sausage: i % 2 === 0,
          },
          beverages: {
            coffee: i % 2 === 0,
            tea: i % 2 === 1,
            hotMilk: i % 4 === 0,
            coldMilk: i % 5 === 0,
          },
          additions: {
            sugar: i !== 3,
            sweetener: i === 3,
            coffeeCreamer: i % 3 === 0,
          },
        }
      } else if (orderData.mealType === 'lunch') {
        const portionOptions: Array<'small' | 'large' | 'vegetarian'> = [
          'small',
          'large',
          'vegetarian',
        ]
        mealData.lunch = {
          portionSize: portionOptions[i % 3],
          soup: i % 2 === 0,
          dessert: true,
          specialPreparations: {
            pureedFood: i === 7,
            pureedMeat: i === 7,
            slicedMeat: i % 3 === 0 && i !== 7,
            mashedPotatoes: i % 4 === 0,
          },
          restrictions: {
            noFish: i === 2,
            fingerFood: i % 6 === 0,
            onlySweet: false,
          },
        }
      } else if (orderData.mealType === 'dinner') {
        mealData.dinner = {
          accordingToPlan: i % 2 === 0,
          bread: {
            greyBread: i % 2 === 0,
            wholeGrainBread: i % 3 === 0,
            whiteBread: i % 4 === 0,
            crispbread: i % 5 === 0,
          },
          preparation: {
            spread: i % 2 === 0,
            sliced: i % 2 === 1,
          },
          spreads: {
            butter: true,
            margarine: i % 3 === 0,
          },
          soup: i % 2 === 0,
          porridge: i === 7,
          noFish: i === 2,
          beverages: {
            tea: i % 2 === 0,
            cocoa: i % 4 === 0,
            hotMilk: i % 3 === 0,
            coldMilk: i % 5 === 0,
          },
          additions: {
            sugar: i !== 3,
            sweetener: i === 3,
          },
        }
      }

      await payload.create({
        collection: 'meals',
        data: mealData,
      })
      totalMeals++
    }

    // Update order meal count
    await payload.update({
      collection: 'meal-orders',
      id: order.id,
      data: {
        mealCount: residentsToUse.length,
      },
    })
  }

  payload.logger.info(`Created ${mealOrders.length} meal orders with ${totalMeals} total meals`)
  payload.logger.info('Database seeding complete!')
  payload.logger.info('')
  payload.logger.info('Login credentials:')
  payload.logger.info('  Admin:     admin@example.com / test')
  payload.logger.info('  Caregiver: caregiver@example.com / test')
  payload.logger.info('  Kitchen:   kitchen@example.com / test')
}
