'use client'

import { useMemo } from 'react'
import { useJWT } from '../jwt/JWTContext'
import {
    createMizanCSRClient,
    Auth,
    type MizanHTTPClient,
    type CSRClientConfig,
} from './index'

// Re-export everything from main entry for convenience
export * from './index'
export * from '../jwt/JWTContext'
export type * from './types'

/**
 * React hook that returns a client-side Django HTTP client.
 *
 * For SESSION auth, creates a session-based client with CSRF handling.
 * For JWT auth, automatically wires up the JWTContext from mizan/jwt.
 *
 * @param auth - Authentication strategy (Auth.SESSION or Auth.JWT)
 * @param config - Optional client configuration
 * @returns MizanHTTPClient
 *
 * @example
 * // Session-based
 * const client = useMizanCSRClient(Auth.SESSION)
 * const user = await client.json('GET', '/api/accounts/me/')
 *
 * @example
 * // JWT-based (requires JWTContext from mizan/jwt)
 * const client = useMizanCSRClient(Auth.JWT)
 * const user = await client.json('GET', '/api/accounts/me/')
 */
export function useMizanCSRClient(auth: Auth, config?: CSRClientConfig): MizanHTTPClient {
    // Always call useJWT (React hooks must be unconditional)
    // Returns null when outside JWTContext
    const jwtContext = useJWT()

    return useMemo(() => {
        if (auth === Auth.JWT) {
            if (!jwtContext?.getAccessToken) {
                throw new Error(
                    'useMizanCSRClient(Auth.JWT) requires JWTContext from mizan/jwt. ' +
                    'Wrap your component in JWTContext to use JWT authentication.'
                )
            }
            return createMizanCSRClient(Auth.JWT, {
                ...config,
                getAccessToken: jwtContext.getAccessToken,
            })
        }

        return createMizanCSRClient(Auth.SESSION, config)
    }, [auth, config, jwtContext?.getAccessToken])
}
