import { describe, it, expect, beforeEach, vi } from 'vitest';
import { renderHook, waitFor } from '@testing-library/react';
import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
import type { ReactNode } from 'react';

vi.mock('../client', () => ({ api: { GET: vi.fn() } }));

import { api as apiClient } from '../client';
import { useAuthCapabilities } from './auth';

function wrapper({ children }: { children: ReactNode }) {
  const qc = new QueryClient({ defaultOptions: { queries: { retry: false } } });
  return <QueryClientProvider client={qc}>{children}</QueryClientProvider>;
}

describe('useAuthCapabilities', () => {
  beforeEach(() => vi.clearAllMocks());

  it('returns the capabilities body on success', async () => {
    (apiClient.GET as any).mockResolvedValue({
      data: {
        oidc: { enabled: true, providerName: 'Logto', primary: true },
        localAccounts: { enabled: true, adminRecoveryOnly: true },
      },
      error: null,
    });

    const { result } = renderHook(() => useAuthCapabilities(), { wrapper });

    await waitFor(() => expect(result.current.isSuccess).toBe(true));
    expect(result.current.data?.oidc?.enabled).toBe(true);
    expect(result.current.data?.oidc?.providerName).toBe('Logto');
    expect(result.current.data?.localAccounts?.adminRecoveryOnly).toBe(true);
  });

  it('exposes error state when the request fails', async () => {
    (apiClient.GET as any).mockResolvedValue({
      data: undefined,
      error: { message: 'boom' },
    });

    const { result } = renderHook(() => useAuthCapabilities(), { wrapper });

    await waitFor(() => expect(result.current.isError).toBe(true));
  });
});
