import { screen, waitFor } from '@testing-library/react'
import { Route, Routes } from 'react-router-dom'
import { describe, expect, it, vi } from 'vitest'

import WikiDiffPage from '@/pages/wiki/WikiDiffPage'
import { renderWithProviders } from '@/test/render'

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

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

describe ('WikiDiffPage', () => {
  it ('fetches and renders wiki diff lines', async () => {
    api.apiGet.mockResolvedValueOnce ({
      wikiPageId:      3,
      title:           '差分対象',
      deprecatedAt:    null,
      olderRevisionId: 1,
      newerRevisionId: 2,
      diff: [
        { type: 'context', content: 'same' },
        { type: 'added', content: 'added line' },
        { type: 'removed', content: 'removed line' },
      ],
    })

    renderWithProviders (
        <Routes>
          <Route path="/wiki/:id/diff" element={<WikiDiffPage/>}/>
        </Routes>,
        { route: '/wiki/3/diff?from=1&to=2' },
    )

    await waitFor (() => {
      expect (api.apiGet).toHaveBeenCalledWith (
          '/wiki/3/diff',
          { params: { from: '1', to: '2' } },
      )
    })
    expect (screen.getByText ('差分対象')).toBeInTheDocument ()
    expect (screen.getByText ('same')).toBeInTheDocument ()
    expect (screen.getByText ('added line')).toBeInTheDocument ()
    expect (screen.getByText ('removed line')).toBeInTheDocument ()
  })

  it ('appends deprecated state to the wiki title', async () => {
    api.apiGet.mockResolvedValueOnce ({
      wikiPageId:      3,
      title:           '廃止 Wiki',
      deprecatedAt:    '2026-06-01T00:00:00.000Z',
      olderRevisionId: 1,
      newerRevisionId: 2,
      diff:            [],
    })

    renderWithProviders (
        <Routes>
          <Route path="/wiki/:id/diff" element={<WikiDiffPage/>}/>
        </Routes>,
        { route: '/wiki/3/diff?from=1&to=2' },
    )

    expect (await screen.findByRole ('heading', {
      name: '廃止 Wiki（廃止）',
    })).toBeInTheDocument ()
  })
})
