import { describe, it, expect, vi } from 'vitest'
import { ref } from 'vue'
import { usePersonalTags } from '../usePersonalTags'
import type { PersonalTag } 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('usePersonalTags', () => {
  it('initial newTag is empty', () => {
    const tags = ref<PersonalTag[]>([])
    const { newTag } = usePersonalTags(12345, tags)
    expect(newTag.value).toBe('')
  })

  it('handleAddTag adds tag and clears input', async () => {
    const { api } = await import('../../api/client')
    vi.mocked(api.post).mockResolvedValue({
      data: { personal_tags: [{ name: 'oncology' }, { name: 'surgery' }] },
    })

    const tags = ref<PersonalTag[]>([])
    const { newTag, handleAddTag } = usePersonalTags(12345, tags)
    newTag.value = 'oncology'
    await handleAddTag()
    expect(tags.value).toHaveLength(2)
    expect(tags.value[0]!.name).toBe('oncology')
    expect(newTag.value).toBe('')
  })

  it('handleAddTag does nothing for empty input', async () => {
    const tags = ref<PersonalTag[]>([])
    const { handleAddTag } = usePersonalTags(12345, tags)
    await handleAddTag()
    expect(tags.value).toHaveLength(0)
  })

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

    const tags = ref<PersonalTag[]>([
      { name: 'oncology' },
      { name: 'surgery' },
    ])
    const { handleRemoveTag } = usePersonalTags(12345, tags)
    await handleRemoveTag('oncology')
    expect(tags.value).toHaveLength(1)
    expect(tags.value[0]!.name).toBe('surgery')
  })
})
