import type { ReactNode } from 'react';
import { createContext, useContext } from 'react';

import type { ContextMe } from '@/client/models/ContextMe';
import { useCurrentUser } from '@/hooks/user/useCurrentUser';

interface UserContextValue {
  user: ContextMe | undefined;
  isLoading: boolean;
  isAuthenticated: boolean;
  refetch: () => void;
}

const UserContext = createContext<UserContextValue | null>(null);

export function UserProvider({ children }: { children: ReactNode }) {
  const { data: user, isLoading, refetch } = useCurrentUser();

  const value: UserContextValue = {
    user,
    isLoading,
    isAuthenticated: !!user,
    refetch,
  };

  return <UserContext.Provider value={value}>{children}</UserContext.Provider>;
}

export function useUserContext(): UserContextValue {
  const ctx = useContext(UserContext);
  if (!ctx) {
    throw new Error('useUserContext must be used within a UserProvider');
  }
  return ctx;
}
