import { fireEvent, screen, waitFor } from '@testing-library/react'
import { describe, expect, it, vi } from 'vitest'

import PostFormTagsArea from '@/components/PostFormTagsArea'
import { buildTag } from '@/test/factories'
import { renderWithProviders } from '@/test/render'

const api = vi.hoisted (() => ({
  apiGet: vi.fn (),
}))

vi.mock ('@/lib/api', () => api)

describe ('PostFormTagsArea', () => {
  it ('updates text and fetches autocomplete for the selected token', async () => {
    const setTags = vi.fn ()
    api.apiGet.mockResolvedValueOnce ([buildTag ({ name: '虹夏', postCount: 3 })])

    renderWithProviders (<PostFormTagsArea tags="虹" setTags={setTags}/>)

    const textarea = screen.getByRole ('textbox')
    fireEvent.focus (textarea)
    fireEvent.select (textarea, { target: { selectionStart: 1, selectionEnd: 1 } })
    fireEvent.change (textarea, { target: { value: '虹夏' } })

    await waitFor (() => {
      expect (api.apiGet).toHaveBeenCalledWith (
          '/tags/autocomplete',
          { params: { q: '虹', nico: '0' } },
      )
    })
    expect (setTags).toHaveBeenCalledWith ('虹夏')
  })
})
