import { describe, it, expect, vi, beforeEach } from 'vitest'
import { setActivePinia, createPinia } from 'pinia'
import { useSoftwareStore } from '../software.store'

const mockIndex = vi.fn().mockResolvedValue([
  { software: { name: 'test-game', title: 'Test Game', status: 'released', platform: 'tic80', author: 'dev' }, releases: [], totalDownloads: 0 },
])

vi.mock('../../api/software.api', () => ({
  default: {
    index: (...args: unknown[]) => mockIndex(...args),
    highlighted: vi.fn().mockResolvedValue(null),
  },
}))

describe('useSoftwareStore', () => {
  beforeEach(() => {
    setActivePinia(createPinia())
    mockIndex.mockClear()
  })

  it('fetches software items', async () => {
    const store = useSoftwareStore()
    await store.fetch()
    expect(store.items).toHaveLength(1)
    expect(store.items[0].software.name).toBe('test-game')
    expect(store.loading).toBe(false)
  })

  it('caches after first fetch', async () => {
    const store = useSoftwareStore()
    await store.fetch()
    await store.fetch()
    expect(mockIndex).toHaveBeenCalledOnce()
  })

  it('findByName returns correct entry', async () => {
    const store = useSoftwareStore()
    await store.fetch()
    expect(store.findByName('test-game')).toBeDefined()
    expect(store.findByName('nonexistent')).toBeUndefined()
  })
})
