import { describe, it, expect, vi } from 'vitest'
import { useLiteratureDetail } from '../useLiteratureDetail'

const mockApiResponse = (data: unknown) => ({ data })

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

describe('useLiteratureDetail', () => {
  it('initial state is correct before mount', () => {
    const result = useLiteratureDetail(12345)
    expect(result.lit.value).toBeNull()
    expect(result.loading.value).toBe(true)
    expect(result.saving.value).toBe(false)
    expect(result.saved.value).toBe(false)
    expect(result.rating.value).toBe(0)
    expect(result.notes.value).toEqual([])
    expect(result.personalTags.value).toEqual([])
    expect(result.studyTypes.value).toEqual([])
  })

  it('handleSave toggles saved state', async () => {
    const { api } = await import('../../api/client')
    vi.mocked(api.post).mockResolvedValue(mockApiResponse(null))

    const result = useLiteratureDetail(12345)
    expect(result.saved.value).toBe(false)
    await result.handleSave()
    expect(result.saved.value).toBe(true)
    expect(api.post).toHaveBeenCalledWith('/literature/12345/save')

    await result.handleSave()
    expect(result.saved.value).toBe(false)
    expect(api.delete).toHaveBeenCalledWith('/literature/12345/save')
  })

  it('handleRate calls API and updates rating', async () => {
    const { api } = await import('../../api/client')
    vi.mocked(api.post).mockResolvedValue(mockApiResponse(null))

    const result = useLiteratureDetail(12345)
    await result.handleRate(5)
    expect(result.rating.value).toBe(5)
    expect(api.post).toHaveBeenCalledWith('/settings/literature/12345/rate', { rating: 5 })
  })

  it('formatDate returns first 10 chars', () => {
    const result = useLiteratureDetail(12345)
    expect(result.formatDate('2024-01-15T00:00:00Z')).toBe('2024-01-15')
    expect(result.formatDate(null)).toBe('')
    expect(result.formatDate(undefined)).toBe('')
  })

  it('exportOptions returns correct formats', () => {
    const result = useLiteratureDetail(12345)
    expect(result.exportOptions).toHaveLength(4)
    expect(result.exportOptions[0]!.key).toBe('bibtex')
  })
})
