import { describe, it, expect } from 'vitest'
import { mountSuspended, registerEndpoint } from '@nuxt/test-utils/runtime'
import Members from '../../app/pages/members.vue'

const wait = (ms = 100) => new Promise(r => setTimeout(r, ms))

const setupEndpoints = (userResponse) => {
  registerEndpoint('/api/me', userResponse, { method: 'GET' })
  registerEndpoint('/api/users', () => [])
}

describe('members page', () => {
  it('renders Members heading', async () => {
    setupEndpoints(() => null)
    const wrapper = await mountSuspended(Members)
    expect(wrapper.text()).toContain('Members')
  })

  it('shows sign in message when no user', async () => {
    setupEndpoints(() => null)
    const wrapper = await mountSuspended(Members)
    expect(wrapper.text()).toMatch(/Sign in to view members/)
  })

  it.each([
    [
      { id: '1', identifier: 'admin', role: 'admin', avatar_url: null },
      ['Add user', /Only admins can change roles/],
    ],
    [
      { id: '2', identifier: 'leader', role: 'leader', avatar_url: null },
      ['Members', 'Identifier'],
    ],
  ])('shows content for %s role', async (user, expectedTexts) => {
    setupEndpoints(() => user)
    const wrapper = await mountSuspended(Members)
    await wait(user.role === 'leader' ? 150 : 100)
    expectedTexts.forEach((text) => {
      expect(wrapper.text()).toMatch(text)
    })
  })
})
