import { describe, it, expect } from 'vitest'
import { requireAuth } from '../../server/utils/authHelpers.js'

const mockEvent = (user = null) => ({ context: { user } })

describe('authHelpers', () => {
  it('requireAuth throws 401 when no user', () => {
    const event = mockEvent()
    expect(() => requireAuth(event)).toThrow()
    try {
      requireAuth(event)
    }
    catch (e) {
      expect(e.statusCode).toBe(401)
    }
  })

  it('requireAuth returns user when set', () => {
    const user = { id: '1', identifier: 'a@b.com', role: 'member' }
    expect(requireAuth(mockEvent(user))).toEqual(user)
  })

  it.each([
    ['member', 'adminOrLeader', 403],
    ['admin', 'adminOrLeader', null],
    ['leader', 'adminOrLeader', null],
    ['leader', 'admin', 403],
    ['admin', 'admin', null],
  ])('requireAuth with %s role and %s requirement', (userRole, requirement, expectedStatus) => {
    const user = { id: '1', identifier: 'a', role: userRole }
    const event = mockEvent(user)
    if (expectedStatus === null) {
      expect(requireAuth(event, { role: requirement })).toEqual(user)
    }
    else {
      expect(() => requireAuth(event, { role: requirement })).toThrow()
      try {
        requireAuth(event, { role: requirement })
      }
      catch (e) {
        expect(e.statusCode).toBe(expectedStatus)
      }
    }
  })
})
