'use client'

/**
 * Next.js adapter for mizan/jwt.
 *
 * Usage:
 * ```tsx
 * // In layout.tsx
 * import { NextAuthContext } from 'mizan/jwt/nextjs'
 *
 * export default function RootLayout({ children }) {
 *     return (
 *         <NextAuthContext user={user}>
 *             {children}
 *         </NextAuthContext>
 *     )
 * }
 * ```
 */

import { type ReactNode } from 'react'
import { useRouter, usePathname, useSearchParams } from 'next/navigation'
import type { RouterAdapter } from './RouterContext'
import { RouterContext } from './RouterContext'
import { AuthContext, type AuthContextProps } from './AuthContext'
import type { BaseUser, AuthRoutes } from './types'

/**
 * Create a RouterAdapter from Next.js App Router hooks.
 */
export function useNextRouter(): RouterAdapter {
    const router = useRouter()
    const pathname = usePathname()
    const searchParams = useSearchParams()

    return {
        push: (path: string) => router.push(path),
        replace: (path: string) => router.replace(path),
        pathname,
        searchParams: new URLSearchParams(searchParams.toString()),
    }
}

export interface NextAuthContextProps<TUser extends BaseUser = BaseUser> {
    children: ReactNode
    /** Initial user from SSR hydration */
    user?: TUser | null
    /** API endpoint to fetch user data (default: '/api/auth/me/') */
    userEndpoint?: string
    /** Route configuration for guards */
    routes?: Partial<AuthRoutes>
}

/**
 * Next.js-specific AuthContext that handles the router automatically.
 */
export function NextAuthContext<TUser extends BaseUser = BaseUser>({
    children,
    user,
    userEndpoint,
    routes,
}: NextAuthContextProps<TUser>) {
    const router = useNextRouter()

    return (
        <RouterContext router={router}>
            <AuthContext user={user} userEndpoint={userEndpoint} routes={routes}>
                {children}
            </AuthContext>
        </RouterContext>
    )
}
