import { describe, it, expect, vi, beforeEach } from 'vitest'
import { setActivePinia, createPinia } from 'pinia'

vi.mock('@/api/authApi', () => ({
  authApi: {
    signupEnabled: vi.fn(() => Promise.resolve({ enabled: true })),
  },
}))

import { authApi } from '@/api/authApi'
import { useUiStore } from '@/stores/ui'

describe('ui 스토어', () => {
  beforeEach(() => setActivePinia(createPinia()))

  it('openLogin: 로그인 열고 회원가입 닫고 redirect 보존', () => {
    const ui = useUiStore()
    ui.signupOpen = true
    ui.openLogin('/account/entries')
    expect(ui.loginOpen).toBe(true)
    expect(ui.signupOpen).toBe(false)
    expect(ui.redirectPath).toBe('/account/entries')
  })

  it('closeLogin: 닫고 redirect 초기화', () => {
    const ui = useUiStore()
    ui.openLogin('/x')
    ui.closeLogin()
    expect(ui.loginOpen).toBe(false)
    expect(ui.redirectPath).toBe('')
  })

  it('openSignup: 회원가입 열고 로그인 닫고 허용여부 재조회', () => {
    const ui = useUiStore()
    ui.loginOpen = true
    ui.openSignup()
    expect(ui.signupOpen).toBe(true)
    expect(ui.loginOpen).toBe(false)
    expect(authApi.signupEnabled).toHaveBeenCalled()
  })

  it('toggleSidebar / closeSidebar', () => {
    const ui = useUiStore()
    expect(ui.sidebarOpen).toBe(false)
    ui.toggleSidebar()
    expect(ui.sidebarOpen).toBe(true)
    ui.closeSidebar()
    expect(ui.sidebarOpen).toBe(false)
  })

  it('loadSignupEnabled: API 값 반영', async () => {
    authApi.signupEnabled.mockResolvedValueOnce({ enabled: false })
    const ui = useUiStore()
    await ui.loadSignupEnabled()
    expect(ui.signupEnabled).toBe(false)
  })

  it('loadSignupEnabled: 조회 실패 시 기본 허용(true)', async () => {
    authApi.signupEnabled.mockRejectedValueOnce(new Error('net'))
    const ui = useUiStore()
    await ui.loadSignupEnabled()
    expect(ui.signupEnabled).toBe(true)
  })
})
