"use client";

import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
import { useDataProvider, useQueryKeyPrefix } from '@/lib/demo/data-provider-context';
import { useRouter } from 'next/navigation';

export function useCurrentUser() {
  const { auth } = useDataProvider();
  const qk = useQueryKeyPrefix();
  return useQuery({
    queryKey: qk('auth', 'user'),
    queryFn: () => auth.getCurrentUser(),
    retry: false,
    staleTime: 5 * 60 * 1000, // 5 minutes
  });
}

export function useLogout() {
  const queryClient = useQueryClient();
  const router = useRouter();
  const { auth, basePath } = useDataProvider();

  return useMutation({
    mutationFn: () => auth.logout(),
    onSuccess: () => {
      queryClient.clear();
      // In demo mode, redirect to /demo; in real mode, redirect to /login
      if (basePath.startsWith('/demo')) {
        router.push('/demo');
      } else {
        router.push('/login');
      }
    },
  });
}
