import { describe, it, expect } from 'vitest'
import { mountSuspended, registerEndpoint } from '@nuxt/test-utils/runtime'
import Index from '../../app/pages/index.vue'
import Login from '../../app/pages/login.vue'

const wait = (ms = 200) => new Promise(r => setTimeout(r, ms))

const setupProtectedEndpoints = () => {
  registerEndpoint('/api/cameras', () => ({ devices: [], liveSessions: [] }), { method: 'GET' })
  registerEndpoint('/api/pois', () => [], { method: 'GET' })
}

describe('auth middleware', () => {
  it('allows /login without redirect when unauthenticated', async () => {
    registerEndpoint('/api/me', () => null, { method: 'GET' })
    const wrapper = await mountSuspended(Login)
    expect(wrapper.text()).toContain('Sign in')
    expect(wrapper.find('input[type="password"]').exists()).toBe(true)
  })

  it.each([
    [() => null, '/login', { redirect: '/' }],
    [
      () => {
        throw createError({ statusCode: 401 })
      },
      '/login',
      undefined,
    ],
  ])('redirects to /login when unauthenticated: %s', async (meResponse, expectedPath, expectedQuery) => {
    registerEndpoint('/api/me', meResponse, { method: 'GET' })
    setupProtectedEndpoints()
    await mountSuspended(Index)
    await wait(meResponse.toString().includes('401') ? 250 : 200)
    const router = useRouter()
    await router.isReady()
    expect(router.currentRoute.value.path).toBe(expectedPath)
    if (expectedQuery) {
      expect(router.currentRoute.value.query).toMatchObject(expectedQuery)
    }
  })
})
