/**
 * (context value: session vs null; hook guard outside provider).
 */
import React from 'react'
import { render, screen } from '@testing-library/react'
import { AuthSessionProvider, useAuthSession } from '../auth-session-provider'

const mockAuthSession = {
  access_token: 'token',
  id_token: 'id',
  refresh_token: 'refresh',
  refresh_at: Date.now() + 3600000,
  user: { fullname: 'User', sub: 'sub', org_id: 'o1' },
}

function Consumer() {
  const { authSession } = useAuthSession()
  return <span>{authSession ? authSession.user?.fullname : 'null'}</span>
}

describe('[providers/auth-session-provider] AuthSessionProvider', () => {
  describe('happy path', () => {
    it('provides authSession to descendants', () => {
      render(
        <AuthSessionProvider authSession={mockAuthSession}>
          <Consumer />
        </AuthSessionProvider>,
      )
      expect(screen.getByText('User')).toBeInTheDocument()
    })

    it('provides null session when prop is null', () => {
      render(
        <AuthSessionProvider authSession={null}>
          <Consumer />
        </AuthSessionProvider>,
      )
      expect(screen.getByText('null')).toBeInTheDocument()
    })
  })

  describe('errors', () => {
    it('throws when useAuthSession is used outside provider', () => {
      expect(() => render(<Consumer />)).toThrow(
        'useAuth must be used within AuthProvider',
      )
    })
  })
})
