import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import { createPinia, setActivePinia } from 'pinia'
import { fetchActivity } from '../src/api/activity'
import { queryClient } from '../src/api/queryClient'
import { useAuthStore } from '../src/stores/auth'

beforeEach(() => {
  setActivePinia(createPinia())
  const auth = useAuthStore()
  auth.initialized = true
  auth.applySession({
    accessToken: 'activity-access-token',
    expiresAt: '2026-07-31T12:00:00.000Z',
    user: {
      id: 'bao',
      email: 'bao@nexus.local',
      displayName: 'Bao',
      role: 'owner',
    },
  })
  queryClient.clear()
})

afterEach(() => {
  queryClient.clear()
  vi.unstubAllGlobals()
})

describe('activity query contract', () => {
  it('preserves the backend entity reference for result navigation', async () => {
    vi.stubGlobal('fetch', vi.fn(async () => new Response(JSON.stringify({
      items: [{
        id: 42,
        type: 'TaskUpdated',
        message: 'Task moved to review.',
        at: '2026-07-31T10:00:00.000Z',
        entity: {
          type: 'task',
          id: '11111111-1111-4111-8111-111111111111',
          label: null,
        },
      }],
      totalCount: 1,
      page: 1,
      pageSize: 200,
      totalPages: 1,
    }), {
      status: 200,
      headers: { 'Content-Type': 'application/json' },
    })))

    const activity = await fetchActivity()

    expect(activity.items[0]?.entity).toEqual({
      type: 'task',
      id: '11111111-1111-4111-8111-111111111111',
      label: null,
    })
  })
})
