import { describe, it, expect, vi } from 'vitest'
import { ref } from 'vue'
import { useLiteratureNotes } from '../useLiteratureNotes'
import type { NoteItem } from '../../types'

vi.mock('../../api/client', () => ({
  api: { post: vi.fn(), delete: vi.fn() },
}))
vi.mock('../useToast', () => ({
  useToast: () => ({ apiError: vi.fn(), success: vi.fn(), error: vi.fn(), warning: vi.fn(), info: vi.fn() }),
}))

describe('useLiteratureNotes', () => {
  it('initial state has empty content and not saving', () => {
    const notes = ref<NoteItem[]>([])
    const { noteContent, noteSaving } = useLiteratureNotes(12345, notes)
    expect(noteContent.value).toBe('')
    expect(noteSaving.value).toBe(false)
  })

  it('handleAddNote prepends to notes ref', async () => {
    const { api } = await import('../../api/client')
    const newNote: NoteItem = {
      id: 'note1', content: 'test note', created_at: '2024-01-01T00:00:00Z',
    }
    vi.mocked(api.post).mockResolvedValue({ data: newNote })

    const notes = ref<NoteItem[]>([])
    const { noteContent, handleAddNote } = useLiteratureNotes(12345, notes)
    noteContent.value = 'test note'
    await handleAddNote()
    expect(notes.value).toHaveLength(1)
    expect(notes.value[0]!.content).toBe('test note')
    expect(noteContent.value).toBe('')
  })

  it('handleAddNote does nothing for empty content', async () => {
    const notes = ref<NoteItem[]>([])
    const { handleAddNote } = useLiteratureNotes(12345, notes)
    await handleAddNote()
    expect(notes.value).toHaveLength(0)
  })

  it('handleDeleteNote removes from notes ref', async () => {
    const { api } = await import('../../api/client')
    vi.mocked(api.delete).mockResolvedValue({})

    const notes = ref<NoteItem[]>([
      { id: 'n1', content: 'first', created_at: '2024-01-01' },
      { id: 'n2', content: 'second', created_at: '2024-01-02' },
    ])
    const { handleDeleteNote } = useLiteratureNotes(12345, notes)
    await handleDeleteNote('n1')
    expect(notes.value).toHaveLength(1)
    expect(notes.value[0]!.id).toBe('n2')
  })
})
