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

import PostNewPage from '@/pages/posts/PostNewPage'
import { buildUser } from '@/test/factories'
import { renderWithProviders } from '@/test/render'

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

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

describe ('PostNewPage', () => {
  beforeEach (() => {
    vi.clearAllMocks ()
    api.isApiError.mockReturnValue (false)
    api.apiGet.mockResolvedValue ({
      url: 'https://example.com/post',
      title: 'post',
      tags: '' })
    sessionStorage.clear ()
  })

  it ('shows the source page on /posts/new', () => {
    renderWithProviders (<PostNewPage user={buildUser ()}/>, {
      route: '/posts/new' })

    expect (screen.getByRole ('heading', { name: '広場に投稿を追加' })).toBeInTheDocument ()
  })

  it ('shows the review page when query state is present', () => {
    renderWithProviders (<PostNewPage user={buildUser ()}/>, {
      route: '/posts/new?urls=https%3A%2F%2Fexample.com%2Fpost' })

    expect (screen.getByRole ('heading', { name: '追加内容確認' })).toBeInTheDocument ()
    expect (screen.queryByText ('広場に投稿を追加')).not.toBeInTheDocument ()
  })
})
