// The portal auth GATE, tested at the loader. Server-side (a `query` fn is
// present) it asks the api's `session.me`: an anonymous identity must throw
// RedirectError to /login; a `user` identity resolves with the tenant. On a
// client navigation (`query` undefined) it resolves permissively.

import { describe, expect, test, vi } from 'vitest'
import { RedirectError } from '@voltro/web'
import { loader } from './layout'
import type { Identity } from '../../lib/api'

const queryReturning = (identity: Identity) =>
  vi.fn(async (_tag: string, _input: unknown) => identity as unknown)

describe('portal gate — loader', () => {
  test('redirects an anonymous caller to /login', async () => {
    const query = queryReturning({ type: 'anonymous', id: null, tenantId: null })
    await expect(loader({ query } as never)).rejects.toBeInstanceOf(RedirectError)
    expect(query).toHaveBeenCalledWith('session.me', {})
  })

  test('lets a signed-in user through and returns the tenant', async () => {
    const query = queryReturning({ type: 'user', id: 'u_1', tenantId: 'acme' })
    const data = await loader({ query } as never)
    expect(data).toEqual({ tenantId: 'acme' })
  })

  test('client navigation (no server query fn) resolves without re-gating', async () => {
    const data = await loader({ query: undefined } as never)
    expect(data).toEqual({ tenantId: null })
  })
})
