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

describe('Round.configJson.useBalancedRanking', () => {
  let programId: string
  let admin: { id: string; email: string; role: 'SUPER_ADMIN' }
  const userIds: string[] = []

  beforeAll(async () => {
    const program = await createTestProgram({ name: `bal-toggle-${uid()}` })
    programId = program.id
    const adminUser = await createTestUser('SUPER_ADMIN')
    userIds.push(adminUser.id)
    admin = { id: adminUser.id, email: adminUser.email, role: 'SUPER_ADMIN' }
  })

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

  it('persists useBalancedRanking via round.update', async () => {
    const competition = await createTestCompetition(programId)
    const round = await createTestRound(competition.id)
    const caller = createCaller(roundRouter, admin)
    await caller.update({
      id: round.id,
      configJson: { useBalancedRanking: false },
    })
    const reloaded = await prisma.round.findUniqueOrThrow({ where: { id: round.id } })
    expect((reloaded.configJson as Record<string, unknown>).useBalancedRanking).toBe(false)
  })
})
