import { afterAll, describe, expect, it } from 'vitest'
import { prisma, createCaller } from '../setup'
import { createTestUser, createTestProgram, cleanupTestData, uid } from '../helpers'
import { lunchRouter } from '@/server/routers/lunch'

describe('lunch.listDishes permission', () => {
  const programIds: string[] = []
  const userIds: string[] = []
  afterAll(async () => {
    for (const id of programIds) {
      await prisma.dish.deleteMany({ where: { lunchEvent: { programId: id } } })
      await prisma.lunchEvent.deleteMany({ where: { programId: id } })
      await cleanupTestData(id, [])
    }
    if (userIds.length) await prisma.user.deleteMany({ where: { id: { in: userIds } } })
  })

  it('lets a non-admin (APPLICANT) read the dish list', async () => {
    const program = await createTestProgram({ name: `dish-perm-${uid()}` })
    programIds.push(program.id)
    const event = await prisma.lunchEvent.create({
      data: { programId: program.id, enabled: true },
    })
    await prisma.dish.create({ data: { lunchEventId: event.id, name: 'Sea bass', sortOrder: 0 } })

    const applicant = await createTestUser('APPLICANT')
    userIds.push(applicant.id)
    const caller = createCaller(lunchRouter, {
      id: applicant.id, email: applicant.email, role: 'APPLICANT',
    })
    const dishes = await caller.listDishes({ lunchEventId: event.id })
    expect(dishes).toHaveLength(1)
    expect(dishes[0].name).toBe('Sea bass')
  })
})
