import { describe, it, expect, vi, beforeEach } from 'vitest'
import { render, screen, waitFor } from '@testing-library/react'
import App from '../src/App'

const fetchMock = vi.fn()

beforeEach(() => {
  fetchMock.mockReset()
  vi.stubGlobal('fetch', fetchMock)
  window.history.replaceState(null, '', '/')
})

function json(status: number, body: unknown) {
  return new Response(JSON.stringify(body), {
    status,
    headers: { 'content-type': 'application/json' },
  })
}

describe('App', () => {
  it('renders the app title', async () => {
    fetchMock.mockImplementation((url: string) => {
      if (url === '/api/setup') return Promise.resolve(json(200, { needed: false }))
      if (url === '/api/me')
        return Promise.resolve(json(200, { user: { id: 1, username: 'sam', isAdmin: true } }))
      return Promise.resolve(json(404, {}))
    })
    render(<App />)
    await waitFor(() => expect(screen.getByRole('heading', { name: 'record-shop' })).toBeTruthy())
  })
})
