import { describe, it, expect, vi, beforeEach } from 'vitest'
import { useSaveLiterature } from '../useSaveLiterature'
import { api } from '../../api/client'

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

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

  it('starts with isSaving false', () => {
    const { isSaving } = useSaveLiterature()
    expect(isSaving.value).toBe(false)
  })

  it('toggleSave calls api.post when not saved', async () => {
    vi.mocked(api.post).mockResolvedValue({ data: {} } as any)
    const { toggleSave } = useSaveLiterature()
    const result = await toggleSave(12345, false)
    expect(api.post).toHaveBeenCalledWith('/literature/12345/save')
    expect(result).toBe(true)
  })

  it('toggleSave calls api.delete when already saved', async () => {
    vi.mocked(api.delete).mockResolvedValue({ data: {} } as any)
    const { toggleSave } = useSaveLiterature()
    const result = await toggleSave(12345, true)
    expect(api.delete).toHaveBeenCalledWith('/literature/12345/save')
    expect(result).toBe(false)
  })

  it('sets isSaving during request', async () => {
    let resolvePromise!: () => void
    vi.mocked(api.post).mockReturnValue(new Promise(r => { resolvePromise = () => r({ data: {} } as any) }) as any)
    const { isSaving, toggleSave } = useSaveLiterature()
    const promise = toggleSave(12345, false)
    expect(isSaving.value).toBe(true)
    resolvePromise()
    await promise
    expect(isSaving.value).toBe(false)
  })

  it('returns original saved state on error', async () => {
    vi.mocked(api.post).mockRejectedValue(new Error('Network error'))
    const { toggleSave } = useSaveLiterature()
    const result = await toggleSave(12345, false)
    expect(result).toBe(false) // original state preserved
  })
})
