import { describe, it, expect, vi, beforeEach } from 'vitest'
import { render, screen, waitFor } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import { Provider } from 'react-redux'
import { MemoryRouter } from 'react-router-dom'
import { configureStore } from '@reduxjs/toolkit'
import authReducer from '../store/slices/authSlice'
import UserListPage from '../pages/usr/UserListPage'

vi.mock('../api/usr', () => ({
  getStaffs: vi.fn().mockResolvedValue([]),
  getPermissionGroups: vi.fn().mockResolvedValue([]),
  createUser: vi.fn()
}))

vi.mock('../api/request', () => ({
  default: { get: vi.fn(), post: vi.fn() }
}))

function makeStore(userType: string) {
  const store = configureStore({ reducer: { auth: authReducer } })
  store.dispatch({
    type: 'auth/setCredentials',
    payload: {
      accessToken: 'test-token',
      refreshToken: 'test-refresh',
      userInfo: { userId: 'u1', username: 'admin', userType, language: '中文', brandId: 'b1' }
    }
  })
  return store
}

function renderPage(userType: string) {
  const store = makeStore(userType)
  return render(
    <Provider store={store}>
      <MemoryRouter>
        <UserListPage />
      </MemoryRouter>
    </Provider>
  )
}

describe('UserListPage', () => {
  beforeEach(() => {
    vi.clearAllMocks()
  })

  it('superAdmin_seesNewButton', () => {
    renderPage('超级管理员')
    expect(screen.getByRole('button', { name: /新\s*增/ })).toBeInTheDocument()
  })

  it('normalUser_doesNotSeeNewButton', () => {
    renderPage('普通用户')
    expect(screen.queryByRole('button', { name: /新\s*增/ })).not.toBeInTheDocument()
  })

  it('clickNewButton_opensDrawer', async () => {
    renderPage('超级管理员')
    await userEvent.click(screen.getByRole('button', { name: /新\s*增/ }))
    await waitFor(() => expect(screen.getByText('新增用户')).toBeInTheDocument())
  })
})
