import { describe, it, expect, vi, beforeEach } from 'vitest'
import { createPinia, setActivePinia } from 'pinia'
import { useProfilesStore } from '@/stores/profiles.js'

vi.mock('@/api/index.js', () => ({
  getProfiles: vi.fn(),
}))

import * as api from '@/api/index.js'

describe('Profiles store', () => {
  beforeEach(() => {
    setActivePinia(createPinia())
    vi.clearAllMocks()
  })

  it('fetchProfiles loads and selects first', async () => {
    api.getProfiles.mockResolvedValue([
      { id: 'secretary', name: 'Secretary' },
      { id: 'developer', name: 'Developer' },
    ])
    const store = useProfilesStore()
    await store.fetchProfiles()
    expect(store.profiles).toHaveLength(2)
    expect(store.selectedProfileId).toBe('secretary')
    expect(store.loading).toBe(false)
  })

  it('fetchProfiles does not overwrite selection', async () => {
    api.getProfiles.mockResolvedValue([
      { id: 'secretary' },
      { id: 'developer' },
    ])
    const store = useProfilesStore()
    store.selectedProfileId = 'developer'
    await store.fetchProfiles()
    expect(store.selectedProfileId).toBe('developer')
  })

  it('getProfile finds by id', async () => {
    api.getProfiles.mockResolvedValue([{ id: 's', name: 'S' }])
    const store = useProfilesStore()
    await store.fetchProfiles()
    expect(store.getProfile('s')).toEqual({ id: 's', name: 'S' })
    expect(store.getProfile('x')).toBeNull()
  })
})
