import { sessionQueries } from '@/service/queries';
import { ClientSession } from '@lib/auth-client';
import { useQuery } from '@tanstack/react-query';
import { createContext, useContext, useMemo } from 'react';

export type UserContext = {
  session: ClientSession;
  isAuth: boolean;
  isAdmin: boolean;
  isPending: boolean;
  error: Error | null;
};

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

export function AuthProvider({ children }: { children: React.ReactNode }) {
  const { data: session, isPending, error } = useQuery(sessionQueries.user());

  const contextSession: UserContext = useMemo(
    () => ({
      session: session as ClientSession,
      isPending,
      error,
      isAuth: !!session,
      isAdmin: session?.user?.role ? session.user.role === 'admin' : false,
    }),
    [session],
  );

  return (
    <AuthContext.Provider value={contextSession}>
      {children}
    </AuthContext.Provider>
  );
}
export function useAuth() {
  const ctx = useContext(AuthContext);
  if (!ctx) {
    throw new Error('useAuth must be used within an AuthProvider');
  }
  return ctx;
}
