import { afterEach, describe, expect, it, vi } from 'vitest'

function installBrowser(token?: string) {
  Object.defineProperty(globalThis, 'window', {
    configurable: true,
    value: {
      localStorage: {
        getItem: vi.fn(() => token ?? null),
      },
    },
  })
}

afterEach(() => {
  vi.restoreAllMocks()
  Reflect.deleteProperty(globalThis, 'window')
  Reflect.deleteProperty(globalThis, 'fetch')
  vi.resetModules()
})

describe('dashboard apiFetch', () => {
  it('adds JSON headers and sends cookies for browser requests', async () => {
    installBrowser()
    const fetchMock = vi.fn(async () => ({
      ok: true,
      json: async () => ({ data: { ok: true } }),
    }))
    Object.defineProperty(globalThis, 'fetch', { configurable: true, value: fetchMock })

    const { apiFetch } = await import('./api')
    await expect(apiFetch('/team')).resolves.toEqual({ ok: true })

    expect(fetchMock).toHaveBeenCalledWith(expect.stringMatching(/\/api\/v1\/team$/), expect.objectContaining({
      credentials: 'include',
      headers: expect.objectContaining({
        'Content-Type': 'application/json',
      }),
    }))
  })

  it('does not force JSON content type for FormData payloads', async () => {
    installBrowser()
    const fetchMock = vi.fn(async () => ({ ok: true, json: async () => ({ data: { uploaded: true } }) }))
    Object.defineProperty(globalThis, 'fetch', { configurable: true, value: fetchMock })

    const { apiFetch } = await import('./api')
    await apiFetch('/uploads', { method: 'POST', body: new FormData() })

    expect((fetchMock as any).mock.calls[0]?.[1].headers).not.toHaveProperty('Content-Type')
    expect((fetchMock as any).mock.calls[0]?.[1]).toEqual(expect.objectContaining({ credentials: 'include' }))
  })

  it('surfaces API error details on failed responses', async () => {
    installBrowser()
    Object.defineProperty(globalThis, 'fetch', {
      configurable: true,
      value: vi.fn(async () => ({
        ok: false,
        status: 403,
        json: async () => ({ message: 'Forbidden', error: 'FORBIDDEN' }),
      })),
    })

    const { apiFetch } = await import('./api')
    await expect(apiFetch('/team')).rejects.toMatchObject({ message: 'Forbidden', code: 'FORBIDDEN', statusCode: 403 })
  })

  it('uses explicit server token and disables caching for server requests', async () => {
    Reflect.deleteProperty(globalThis, 'window')
    const fetchMock = vi.fn(async () => ({ ok: true, json: async () => ({ data: { ok: true } }) }))
    Object.defineProperty(globalThis, 'fetch', { configurable: true, value: fetchMock })

    const { apiFetchServer } = await import('./api')
    await apiFetchServer('/fleet', 'server-token')

    expect(fetchMock).toHaveBeenCalledWith('http://localhost:4000/api/v1/fleet', expect.objectContaining({
      cache: 'no-store',
      headers: expect.objectContaining({ Authorization: 'Bearer server-token' }),
    }))
  })
})
