import { describe, it, expect, beforeAll, afterAll } from 'vitest'
import { prisma, createCaller } from '../setup'
import { createTestProgram, createTestUser, cleanupTestData, uid } from '../helpers'
import { userRouter } from '../../src/server/routers/user'

/**
 * Regression: user-creation paths must populate roles[] with the primary role,
 * so the invariant role ∈ roles holds for new users (prevents the empty-roles[]
 * inconsistency that made primary-role mentors un-addable). Covers the admin
 * `user.create` path as the representative case.
 */
describe('user.create — populates roles[] with the primary role', () => {
  let programId = ''
  const userIds: string[] = []

  beforeAll(async () => {
    const program = await createTestProgram()
    programId = program.id
  })

  afterAll(async () => {
    await cleanupTestData(programId, userIds)
  })

  it('sets roles=[role] on an admin-created user', async () => {
    const admin = await createTestUser('SUPER_ADMIN')
    userIds.push(admin.id)
    const caller = createCaller(userRouter, {
      id: admin.id,
      email: admin.email,
      role: 'SUPER_ADMIN',
    })

    const email = `${uid('created')}@test.local`
    await caller.create({ email, name: 'New Member', role: 'JURY_MEMBER' })

    const created = await prisma.user.findUnique({ where: { email } })
    expect(created).not.toBeNull()
    if (created) userIds.push(created.id)
    expect(created?.role).toBe('JURY_MEMBER')
    expect(created?.roles).toEqual(['JURY_MEMBER'])
  })
})
