import { describe, it, expect, beforeEach, vi } from 'vitest'
import { SessionManager } from '../server/manager'
import { Session } from '../server/session'
import type { SupabaseClient } from '../../../supabase'

describe('SessionManager', () => {
  let mockDb: SupabaseClient
  let sessionManager: SessionManager

  beforeEach(() => {
    // Create mock Supabase client
    mockDb = {
      from: vi.fn()
    } as unknown as SupabaseClient

    sessionManager = new SessionManager(mockDb)
  })

  describe('create', () => {
    it('creates a new session with all parameters', async () => {
      const mockSessionData = {
        session_id: 'session-123',
        resource_id: 'agent-1',
        organization_id: 'org-123',
        user_id: 'user-123',
        memory_snapshot: { sessionMemory: {}, history: [] },
        metadata: { foo: 'bar' },
        session_total_turns: 0,
        created_at: '2025-01-01T00:00:00Z',
        updated_at: '2025-01-01T00:00:00Z'
      }

      const mockInsert = vi.fn().mockReturnValue({
        select: vi.fn().mockReturnValue({
          single: vi.fn().mockResolvedValue({ data: mockSessionData, error: null })
        })
      })

      ;(mockDb.from as ReturnType<typeof vi.fn>).mockReturnValue({
        insert: mockInsert
      })

      const session = await sessionManager.create({
        resourceId: 'agent-1',
        organizationId: 'org-123',
        userId: 'user-123',
        metadata: { foo: 'bar' }
      })

      expect(mockDb.from).toHaveBeenCalledWith('sessions')
      expect(mockInsert).toHaveBeenCalledWith({
        resource_id: 'agent-1',
        organization_id: 'org-123',
        user_id: 'user-123',
        memory_snapshot: { sessionMemory: {}, history: [] },
        metadata: { foo: 'bar' },
        session_total_turns: 0
      })
      expect(session).toBeInstanceOf(Session)
      expect(session.sessionId).toBe('session-123')
      expect(session.organizationId).toBe('org-123')
    })

    it('creates session without userId (optional)', async () => {
      const mockSessionData = {
        session_id: 'session-123',
        resource_id: 'agent-1',
        organization_id: 'org-123',
        user_id: null,
        memory_snapshot: { sessionMemory: {}, history: [] },
        metadata: null,
        session_total_turns: 0,
        created_at: '2025-01-01T00:00:00Z',
        updated_at: '2025-01-01T00:00:00Z'
      }

      const mockInsert = vi.fn().mockReturnValue({
        select: vi.fn().mockReturnValue({
          single: vi.fn().mockResolvedValue({ data: mockSessionData, error: null })
        })
      })

      ;(mockDb.from as ReturnType<typeof vi.fn>).mockReturnValue({
        insert: mockInsert
      })

      const session = await sessionManager.create({
        resourceId: 'agent-1',
        organizationId: 'org-123'
      })

      expect(mockInsert).toHaveBeenCalledWith({
        resource_id: 'agent-1',
        organization_id: 'org-123',
        user_id: null,
        memory_snapshot: { sessionMemory: {}, history: [] },
        metadata: null,
        session_total_turns: 0
      })
      expect(session.userId).toBeNull()
    })

    it('throws error when database insert fails', async () => {
      const mockInsert = vi.fn().mockReturnValue({
        select: vi.fn().mockReturnValue({
          single: vi.fn().mockResolvedValue({
            data: null,
            error: { message: 'Database connection failed' }
          })
        })
      })

      ;(mockDb.from as ReturnType<typeof vi.fn>).mockReturnValue({
        insert: mockInsert
      })

      await expect(
        sessionManager.create({
          resourceId: 'agent-1',
          organizationId: 'org-123'
        })
      ).rejects.toThrow('Failed to create session: Database connection failed')
    })
  })

  describe('get', () => {
    it('retrieves session by ID and organization', async () => {
      const mockSessionData = {
        session_id: 'session-123',
        resource_id: 'agent-1',
        organization_id: 'org-123',
        user_id: 'user-123',
        memory_snapshot: { sessionMemory: {}, history: [] },
        metadata: null,
        session_total_turns: 0,
        created_at: '2025-01-01T00:00:00Z',
        updated_at: '2025-01-01T00:00:00Z'
      }

      const mockIs = vi.fn().mockReturnValue({
        single: vi.fn().mockResolvedValue({ data: mockSessionData, error: null })
      })

      const mockSelect = vi.fn().mockReturnValue({
        eq: vi.fn().mockReturnValue({
          eq: vi.fn().mockReturnValue({
            is: mockIs
          })
        })
      })

      ;(mockDb.from as ReturnType<typeof vi.fn>).mockReturnValue({
        select: mockSelect
      })

      const session = await sessionManager.get('session-123', 'org-123')

      expect(mockDb.from).toHaveBeenCalledWith('sessions')
      expect(session).toBeInstanceOf(Session)
      expect(session!.sessionId).toBe('session-123')
    })

    it('returns null when session not found', async () => {
      const mockIs = vi.fn().mockReturnValue({
        single: vi.fn().mockResolvedValue({
          data: null,
          error: { code: 'PGRST116', message: 'Not found' }
        })
      })

      const mockSelect = vi.fn().mockReturnValue({
        eq: vi.fn().mockReturnValue({
          eq: vi.fn().mockReturnValue({
            is: mockIs
          })
        })
      })

      ;(mockDb.from as ReturnType<typeof vi.fn>).mockReturnValue({
        select: mockSelect
      })

      const session = await sessionManager.get('nonexistent', 'org-123')

      expect(session).toBeNull()
    })

    it('throws error for database errors (not 404)', async () => {
      const mockIs = vi.fn().mockReturnValue({
        single: vi.fn().mockResolvedValue({
          data: null,
          error: { code: 'DB_ERROR', message: 'Connection timeout' }
        })
      })

      const mockSelect = vi.fn().mockReturnValue({
        eq: vi.fn().mockReturnValue({
          eq: vi.fn().mockReturnValue({
            is: mockIs
          })
        })
      })

      ;(mockDb.from as ReturnType<typeof vi.fn>).mockReturnValue({
        select: mockSelect
      })

      await expect(sessionManager.get('session-123', 'org-123')).rejects.toThrow(
        'Failed to get session: Connection timeout'
      )
    })
  })

  describe('list', () => {
    it('lists sessions for organization', async () => {
      const mockSessionsData = [
        {
          session_id: 'session-1',
          resource_id: 'agent-1',
          organization_id: 'org-123',
          user_id: 'user-1',
          memory_snapshot: { sessionMemory: {}, history: [] },
          metadata: null,
          session_total_turns: 0,
          created_at: '2025-01-01T00:00:00Z',
          updated_at: '2025-01-01T00:00:00Z'
        },
        {
          session_id: 'session-2',
          resource_id: 'agent-1',
          organization_id: 'org-123',
          user_id: 'user-2',
          memory_snapshot: { sessionMemory: {}, history: [] },
          metadata: null,
          session_total_turns: 0,
          created_at: '2025-01-01T00:00:00Z',
          updated_at: '2025-01-01T00:00:00Z'
        }
      ]

      const mockLimit = vi.fn().mockResolvedValue({ data: mockSessionsData, error: null })
      const mockOrder = vi.fn().mockReturnValue({ limit: mockLimit })
      const mockIs = vi.fn().mockReturnValue({ order: mockOrder })
      const mockEq = vi.fn().mockReturnValue({ is: mockIs })
      const mockSelect = vi.fn().mockReturnValue({ eq: mockEq })

      ;(mockDb.from as ReturnType<typeof vi.fn>).mockReturnValue({
        select: mockSelect
      })

      const sessions = await sessionManager.list({
        organizationId: 'org-123'
      })

      expect(mockDb.from).toHaveBeenCalledWith('sessions')
      expect(mockEq).toHaveBeenCalledWith('organization_id', 'org-123')
      expect(mockIs).toHaveBeenCalledWith('deleted_at', null)
      expect(mockOrder).toHaveBeenCalledWith('created_at', { ascending: false })
      expect(mockLimit).toHaveBeenCalledWith(50) // Default limit
      expect(sessions).toHaveLength(2)
      expect(sessions[0]).toBeInstanceOf(Session)
    })

    it('filters sessions by userId', async () => {
      const mockSessionsData = [
        {
          session_id: 'session-1',
          resource_id: 'agent-1',
          organization_id: 'org-123',
          user_id: 'user-123',
          memory_snapshot: { sessionMemory: {}, history: [] },
          metadata: null,
          session_total_turns: 0,
          created_at: '2025-01-01T00:00:00Z',
          updated_at: '2025-01-01T00:00:00Z'
        }
      ]

      // Create a mock query builder that chains properly and is awaitable
      const mockQueryBuilder: Record<string, unknown> = {}
      ;(mockQueryBuilder as Record<string, unknown>).eq = vi.fn().mockReturnValue(mockQueryBuilder)
      ;(mockQueryBuilder as Record<string, unknown>).then = vi.fn((resolve: (data: unknown) => void) => {
        resolve({ data: mockSessionsData, error: null })
        return Promise.resolve({ data: mockSessionsData, error: null })
      })

      const mockLimit = vi.fn().mockReturnValue(mockQueryBuilder)
      const mockOrder = vi.fn().mockReturnValue({ limit: mockLimit })
      const mockIs = vi.fn().mockReturnValue({ order: mockOrder })
      const mockOrgEq = vi.fn().mockReturnValue({ is: mockIs })
      const mockSelect = vi.fn().mockReturnValue({ eq: mockOrgEq })

      ;(mockDb.from as ReturnType<typeof vi.fn>).mockReturnValue({
        select: mockSelect
      })

      const sessions = await sessionManager.list({
        organizationId: 'org-123',
        userId: 'user-123'
      })

      expect(mockQueryBuilder.eq).toHaveBeenCalledWith('user_id', 'user-123')
      expect(sessions).toHaveLength(1)
    })

    it('filters sessions by resourceId', async () => {
      const mockSessionsData = [
        {
          session_id: 'session-1',
          resource_id: 'agent-1',
          organization_id: 'org-123',
          user_id: 'user-1',
          memory_snapshot: { sessionMemory: {}, history: [] },
          metadata: null,
          session_total_turns: 0,
          created_at: '2025-01-01T00:00:00Z',
          updated_at: '2025-01-01T00:00:00Z'
        }
      ]

      // Create a mock query builder that chains properly and is awaitable
      const mockQueryBuilder: Record<string, unknown> = {}
      ;(mockQueryBuilder as Record<string, unknown>).eq = vi.fn().mockReturnValue(mockQueryBuilder)
      ;(mockQueryBuilder as Record<string, unknown>).then = vi.fn((resolve: (data: unknown) => void) => {
        resolve({ data: mockSessionsData, error: null })
        return Promise.resolve({ data: mockSessionsData, error: null })
      })

      const mockLimit = vi.fn().mockReturnValue(mockQueryBuilder)
      const mockOrder = vi.fn().mockReturnValue({ limit: mockLimit })
      const mockIs = vi.fn().mockReturnValue({ order: mockOrder })
      const mockOrgEq = vi.fn().mockReturnValue({ is: mockIs })
      const mockSelect = vi.fn().mockReturnValue({ eq: mockOrgEq })

      ;(mockDb.from as ReturnType<typeof vi.fn>).mockReturnValue({
        select: mockSelect
      })

      const sessions = await sessionManager.list({
        organizationId: 'org-123',
        resourceId: 'agent-1'
      })

      expect(mockQueryBuilder.eq).toHaveBeenCalledWith('resource_id', 'agent-1')
      expect(sessions).toHaveLength(1)
    })

    it('respects custom limit parameter', async () => {
      const mockLimit = vi.fn().mockResolvedValue({ data: [], error: null })
      const mockOrder = vi.fn().mockReturnValue({ limit: mockLimit })
      const mockIs = vi.fn().mockReturnValue({ order: mockOrder })
      const mockEq = vi.fn().mockReturnValue({ is: mockIs })
      const mockSelect = vi.fn().mockReturnValue({ eq: mockEq })

      ;(mockDb.from as ReturnType<typeof vi.fn>).mockReturnValue({
        select: mockSelect
      })

      await sessionManager.list({
        organizationId: 'org-123',
        limit: 100
      })

      expect(mockLimit).toHaveBeenCalledWith(100)
    })

    it('throws error when list query fails', async () => {
      const mockLimit = vi.fn().mockResolvedValue({
        data: null,
        error: { message: 'Query timeout' }
      })
      const mockOrder = vi.fn().mockReturnValue({ limit: mockLimit })
      const mockIs = vi.fn().mockReturnValue({ order: mockOrder })
      const mockEq = vi.fn().mockReturnValue({ is: mockIs })
      const mockSelect = vi.fn().mockReturnValue({ eq: mockEq })

      ;(mockDb.from as ReturnType<typeof vi.fn>).mockReturnValue({
        select: mockSelect
      })

      await expect(sessionManager.list({ organizationId: 'org-123' })).rejects.toThrow(
        'Failed to list sessions: Query timeout'
      )
    })
  })

  describe('delete', () => {
    it('deletes session by ID and organization (soft delete)', async () => {
      const mockEq = vi.fn().mockResolvedValue({ error: null })
      const mockUpdate = vi.fn().mockReturnValue({
        eq: vi.fn().mockReturnValue({
          eq: mockEq
        })
      })

      ;(mockDb.from as ReturnType<typeof vi.fn>).mockReturnValue({
        update: mockUpdate
      })

      await sessionManager.delete('session-123', 'org-123')

      expect(mockDb.from).toHaveBeenCalledWith('sessions')
      expect(mockUpdate).toHaveBeenCalledWith(expect.objectContaining({ deleted_at: expect.any(String) }))
    })

    it('throws error when delete fails', async () => {
      const mockEq = vi.fn().mockResolvedValue({
        error: { message: 'Foreign key constraint violation' }
      })
      const mockUpdate = vi.fn().mockReturnValue({
        eq: vi.fn().mockReturnValue({
          eq: mockEq
        })
      })

      ;(mockDb.from as ReturnType<typeof vi.fn>).mockReturnValue({
        update: mockUpdate
      })

      await expect(sessionManager.delete('session-123', 'org-123')).rejects.toThrow(
        'Failed to delete session: Foreign key constraint violation'
      )
    })

    it('enforces organization isolation on delete', async () => {
      const mockSecondEq = vi.fn().mockResolvedValue({ error: null })
      const mockFirstEq = vi.fn().mockReturnValue({
        eq: mockSecondEq
      })
      const mockUpdate = vi.fn().mockReturnValue({
        eq: mockFirstEq
      })

      ;(mockDb.from as ReturnType<typeof vi.fn>).mockReturnValue({
        update: mockUpdate
      })

      await sessionManager.delete('session-123', 'org-456')

      expect(mockFirstEq).toHaveBeenCalledWith('session_id', 'session-123')
      expect(mockSecondEq).toHaveBeenCalledWith('organization_id', 'org-456')
    })
  })

  describe('Concurrency & Race Conditions', () => {
    it('handles multiple simultaneous create operations', async () => {
      let callCount = 0

      // Create a new mock for each call to avoid closure issues
      ;(mockDb.from as ReturnType<typeof vi.fn>).mockImplementation(() => ({
        insert: vi.fn().mockReturnValue({
          select: vi.fn().mockReturnValue({
            single: vi.fn().mockImplementation(async () => {
              const currentId = ++callCount
              // Simulate async delay
              await new Promise((resolve) => setTimeout(resolve, 10))
              return {
                data: {
                  session_id: `session-${currentId}`,
                  resource_id: 'agent-1',
                  organization_id: 'org-123',
                  user_id: 'user-123',
                  memory_snapshot: { sessionMemory: {}, history: [] },
                  metadata: null,
                  session_total_turns: 0,
                  created_at: '2025-01-01T00:00:00Z',
                  updated_at: '2025-01-01T00:00:00Z'
                },
                error: null
              }
            })
          })
        })
      }))

      // Create 5 sessions concurrently
      const promises = Array.from({ length: 5 }, () =>
        sessionManager.create({
          resourceId: 'agent-1',
          organizationId: 'org-123',
          userId: 'user-123'
        })
      )

      const sessions = await Promise.all(promises)

      expect(sessions).toHaveLength(5)
      // Each session should have unique ID
      const ids = sessions.map((s) => s.sessionId)
      expect(new Set(ids).size).toBe(5)
    })

    it('handles concurrent get operations for same session', async () => {
      const mockSessionData = {
        session_id: 'session-123',
        resource_id: 'agent-1',
        organization_id: 'org-123',
        user_id: 'user-123',
        memory_snapshot: { sessionMemory: {}, history: [] },
        metadata: null,
        session_total_turns: 0,
        created_at: '2025-01-01T00:00:00Z',
        updated_at: '2025-01-01T00:00:00Z'
      }

      const mockIs = vi.fn().mockReturnValue({
        single: vi.fn().mockResolvedValue({ data: mockSessionData, error: null })
      })

      const mockSelect = vi.fn().mockReturnValue({
        eq: vi.fn().mockReturnValue({
          eq: vi.fn().mockReturnValue({
            is: mockIs
          })
        })
      })

      ;(mockDb.from as ReturnType<typeof vi.fn>).mockReturnValue({
        select: mockSelect
      })

      // Read same session concurrently
      const promises = Array.from({ length: 10 }, () => sessionManager.get('session-123', 'org-123'))

      const sessions = await Promise.all(promises)

      expect(sessions).toHaveLength(10)
      expect(mockSelect).toHaveBeenCalledTimes(10)
      // All should return session instances
      sessions.forEach((s) => expect(s).toBeInstanceOf(Session))
    })

    it('handles concurrent list operations', async () => {
      const mockSessionsData = [
        {
          session_id: 'session-1',
          resource_id: 'agent-1',
          organization_id: 'org-123',
          user_id: 'user-1',
          memory_snapshot: { sessionMemory: {}, history: [] },
          metadata: null,
          session_total_turns: 0,
          created_at: '2025-01-01T00:00:00Z',
          updated_at: '2025-01-01T00:00:00Z'
        }
      ]

      const mockLimit = vi.fn().mockResolvedValue({ data: mockSessionsData, error: null })
      const mockOrder = vi.fn().mockReturnValue({ limit: mockLimit })
      const mockIs = vi.fn().mockReturnValue({ order: mockOrder })
      const mockEq = vi.fn().mockReturnValue({ is: mockIs })
      const mockSelect = vi.fn().mockReturnValue({ eq: mockEq })

      ;(mockDb.from as ReturnType<typeof vi.fn>).mockReturnValue({
        select: mockSelect
      })

      // Multiple concurrent list requests
      const promises = Array.from({ length: 3 }, () => sessionManager.list({ organizationId: 'org-123' }))

      const results = await Promise.all(promises)

      expect(results).toHaveLength(3)
      expect(mockSelect).toHaveBeenCalledTimes(3)
    })

    it('handles rapid create-then-get sequence', async () => {
      const mockSessionData = {
        session_id: 'session-123',
        resource_id: 'agent-1',
        organization_id: 'org-123',
        user_id: 'user-123',
        memory_snapshot: { sessionMemory: {}, history: [] },
        metadata: null,
        session_total_turns: 0,
        created_at: '2025-01-01T00:00:00Z',
        updated_at: '2025-01-01T00:00:00Z'
      }

      // Mock create
      const mockInsert = vi.fn().mockReturnValue({
        select: vi.fn().mockReturnValue({
          single: vi.fn().mockResolvedValue({ data: mockSessionData, error: null })
        })
      })

      // Mock get
      const mockIs = vi.fn().mockReturnValue({
        single: vi.fn().mockResolvedValue({ data: mockSessionData, error: null })
      })

      const mockSelect = vi.fn().mockReturnValue({
        eq: vi.fn().mockReturnValue({
          eq: vi.fn().mockReturnValue({
            is: mockIs
          })
        })
      })

      ;(mockDb.from as ReturnType<typeof vi.fn>).mockImplementation((table: string) => {
        if (table === 'sessions') {
          return {
            insert: mockInsert,
            select: mockSelect
          }
        }
        return {}
      })

      // Create and immediately get
      const session = await sessionManager.create({
        resourceId: 'agent-1',
        organizationId: 'org-123',
        userId: 'user-123'
      })

      const retrieved = await sessionManager.get(session.sessionId, 'org-123')

      expect(retrieved).not.toBeNull()
      expect(retrieved!.sessionId).toBe(session.sessionId)
    })

    it('handles rapid create-then-delete sequence', async () => {
      const mockSessionData = {
        session_id: 'session-123',
        resource_id: 'agent-1',
        organization_id: 'org-123',
        user_id: 'user-123',
        memory_snapshot: { sessionMemory: {}, history: [] },
        metadata: null,
        session_total_turns: 0,
        created_at: '2025-01-01T00:00:00Z',
        updated_at: '2025-01-01T00:00:00Z'
      }

      const mockInsert = vi.fn().mockReturnValue({
        select: vi.fn().mockReturnValue({
          single: vi.fn().mockResolvedValue({ data: mockSessionData, error: null })
        })
      })

      const mockUpdateEq = vi.fn().mockResolvedValue({ error: null })
      const mockUpdate = vi.fn().mockReturnValue({
        eq: vi.fn().mockReturnValue({
          eq: mockUpdateEq
        })
      })

      ;(mockDb.from as ReturnType<typeof vi.fn>).mockImplementation((table: string) => {
        if (table === 'sessions') {
          return {
            insert: mockInsert,
            update: mockUpdate
          }
        }
        return {}
      })

      const session = await sessionManager.create({
        resourceId: 'agent-1',
        organizationId: 'org-123',
        userId: 'user-123'
      })

      await sessionManager.delete(session.sessionId, 'org-123')

      expect(mockUpdate).toHaveBeenCalledWith(expect.objectContaining({ deleted_at: expect.any(String) }))
    })
  })

  describe('Error Resilience', () => {
    it('handles database connection errors on create', async () => {
      const mockInsert = vi.fn().mockReturnValue({
        select: vi.fn().mockReturnValue({
          single: vi.fn().mockRejectedValue(new Error('Network error'))
        })
      })

      ;(mockDb.from as ReturnType<typeof vi.fn>).mockReturnValue({
        insert: mockInsert
      })

      await expect(
        sessionManager.create({
          resourceId: 'agent-1',
          organizationId: 'org-123'
        })
      ).rejects.toThrow('Network error')
    })

    it('handles database timeout on get', async () => {
      const mockIs = vi.fn().mockReturnValue({
        single: vi.fn().mockRejectedValue(new Error('Query timeout'))
      })

      const mockSelect = vi.fn().mockReturnValue({
        eq: vi.fn().mockReturnValue({
          eq: vi.fn().mockReturnValue({
            is: mockIs
          })
        })
      })

      ;(mockDb.from as ReturnType<typeof vi.fn>).mockReturnValue({
        select: mockSelect
      })

      await expect(sessionManager.get('session-123', 'org-123')).rejects.toThrow('Query timeout')
    })

    it('handles malformed database responses on create', async () => {
      const mockInsert = vi.fn().mockReturnValue({
        select: vi.fn().mockReturnValue({
          single: vi.fn().mockResolvedValue({
            data: null, // Missing data
            error: null // But no error either (malformed response)
          })
        })
      })

      ;(mockDb.from as ReturnType<typeof vi.fn>).mockReturnValue({
        insert: mockInsert
      })

      // If implementation doesn't validate null data, this documents the behavior
      // Either throws TypeError or successfully creates Session with null
      try {
        const result = await sessionManager.create({
          resourceId: 'agent-1',
          organizationId: 'org-123'
        })
        // If it succeeds, Session constructor handles null gracefully
        expect(result).toBeDefined()
      } catch (error) {
        // Or it throws - both behaviors are acceptable for malformed responses
        expect(error).toBeDefined()
      }
    })

    it('handles empty organization ID gracefully', async () => {
      const mockInsert = vi.fn().mockReturnValue({
        select: vi.fn().mockReturnValue({
          single: vi.fn().mockResolvedValue({
            data: null,
            error: { message: 'organization_id cannot be empty' }
          })
        })
      })

      ;(mockDb.from as ReturnType<typeof vi.fn>).mockReturnValue({
        insert: mockInsert
      })

      await expect(
        sessionManager.create({
          resourceId: 'agent-1',
          organizationId: ''
        })
      ).rejects.toThrow('organization_id cannot be empty')
    })

    it('handles null values in required fields', async () => {
      const mockInsert = vi.fn().mockReturnValue({
        select: vi.fn().mockReturnValue({
          single: vi.fn().mockResolvedValue({
            data: null,
            error: { message: 'null value in column "resource_id" violates not-null constraint' }
          })
        })
      })

      ;(mockDb.from as ReturnType<typeof vi.fn>).mockReturnValue({
        insert: mockInsert
      })

      await expect(
        sessionManager.create({
          resourceId: null as unknown,
          organizationId: 'org-123'
        })
      ).rejects.toThrow('null value in column "resource_id"')
    })

    it('handles list with no results gracefully', async () => {
      const mockLimit = vi.fn().mockResolvedValue({ data: [], error: null })
      const mockOrder = vi.fn().mockReturnValue({ limit: mockLimit })
      const mockIs = vi.fn().mockReturnValue({ order: mockOrder })
      const mockEq = vi.fn().mockReturnValue({ is: mockIs })
      const mockSelect = vi.fn().mockReturnValue({ eq: mockEq })

      ;(mockDb.from as ReturnType<typeof vi.fn>).mockReturnValue({
        select: mockSelect
      })

      const sessions = await sessionManager.list({ organizationId: 'org-123' })

      expect(sessions).toEqual([])
    })

    it('handles database returning null data for list', async () => {
      const mockLimit = vi.fn().mockResolvedValue({ data: null, error: null })
      const mockOrder = vi.fn().mockReturnValue({ limit: mockLimit })
      const mockIs = vi.fn().mockReturnValue({ order: mockOrder })
      const mockEq = vi.fn().mockReturnValue({ is: mockIs })
      const mockSelect = vi.fn().mockReturnValue({ eq: mockEq })

      ;(mockDb.from as ReturnType<typeof vi.fn>).mockReturnValue({
        select: mockSelect
      })

      // May throw TypeError when trying to map over null
      try {
        await sessionManager.list({ organizationId: 'org-123' })
        // If it doesn't throw, fail the test
        expect.fail('Expected an error to be thrown')
      } catch (error) {
        expect(error).toBeDefined()
      }
    })
  })
})
