import { describe, it, expect, vi, beforeEach } from 'vitest'
import { sessionsApi } from './sessions'
import apiClient from './client'

vi.mock('./client', () => ({
  default: {
    get: vi.fn(),
    post: vi.fn(),
    put: vi.fn(),
    delete: vi.fn(),
    patch: vi.fn(),
  },
}))

const mockClient = apiClient as unknown as {
  get: ReturnType<typeof vi.fn>
  post: ReturnType<typeof vi.fn>
  delete: ReturnType<typeof vi.fn>
}

beforeEach(() => {
  vi.clearAllMocks()
})

describe('sessionsApi sharing methods', () => {
  it('createShare hits POST /sessions/{id}/shares with correct payload', async () => {
    const mockShare = { id: 'share-1', share_token: 'tok-123', visibility: 'public' }
    mockClient.post.mockResolvedValue({ data: mockShare })

    const payload = { visibility: 'public' as const, share_name: 'My Share' }
    const result = await sessionsApi.createShare('session-42', payload)

    expect(mockClient.post).toHaveBeenCalledWith('/sessions/session-42/shares', payload)
    expect(result).toEqual(mockShare)
  })

  it('listMyShares hits GET /shares/my-shares', async () => {
    const mockShares = [
      { id: 'share-1', share_token: 'tok-1' },
      { id: 'share-2', share_token: 'tok-2' },
    ]
    mockClient.get.mockResolvedValue({ data: mockShares })

    const result = await sessionsApi.listMyShares()

    expect(mockClient.get).toHaveBeenCalledWith('/shares/my-shares')
    expect(result).toEqual(mockShares)
  })

  it('revokeShare hits DELETE /shares/{id}', async () => {
    mockClient.delete.mockResolvedValue({})

    await sessionsApi.revokeShare('share-99')

    expect(mockClient.delete).toHaveBeenCalledWith('/shares/share-99')
  })

  it('getSharedSession hits GET /share/{token}', async () => {
    const mockView = {
      session_id: 'sess-1',
      tree_name: 'DNS Troubleshooting',
      path_taken: ['root', 'node-1'],
      decisions: [],
    }
    mockClient.get.mockResolvedValue({ data: mockView })

    const result = await sessionsApi.getSharedSession('tok-abc')

    expect(mockClient.get).toHaveBeenCalledWith('/share/tok-abc')
    expect(result).toEqual(mockView)
  })
})
