import { describe, it, expect } from 'vitest'
import { resolveAwardWinner } from '@/server/services/award-winner-resolver'

describe('resolveAwardWinner', () => {
  it('returns the sole voted project when all agree', () => {
    const votes = [
      { userId: 'u1', projectId: 'p1' },
      { userId: 'u2', projectId: 'p1' },
    ]
    expect(resolveAwardWinner(votes, 'u1')).toBe('p1')
  })

  it('returns the majority winner when no tie', () => {
    const votes = [
      { userId: 'u1', projectId: 'p1' },
      { userId: 'u2', projectId: 'p2' },
      { userId: 'u3', projectId: 'p1' },
    ]
    expect(resolveAwardWinner(votes, 'u1')).toBe('p1')
  })

  it('uses chair vote as tiebreaker', () => {
    const votes = [
      { userId: 'chair', projectId: 'p2' },
      { userId: 'u2', projectId: 'p1' },
    ]
    expect(resolveAwardWinner(votes, 'chair')).toBe('p2')
  })

  it('returns chair pick when tied and chair voted for one of the tied projects', () => {
    const votes = [
      { userId: 'chair', projectId: 'p3' },
      { userId: 'u2', projectId: 'p1' },
      { userId: 'u3', projectId: 'p2' },
    ]
    expect(resolveAwardWinner(votes, 'chair')).toBe('p3')
  })

  it('returns sole vote for solo sponsor', () => {
    const votes = [{ userId: 'sponsor', projectId: 'p1' }]
    expect(resolveAwardWinner(votes, 'sponsor')).toBe('p1')
  })

  it('throws if no votes', () => {
    expect(() => resolveAwardWinner([], 'chair')).toThrow()
  })
})
