'use client';

import { useQuery, UseQueryResult } from '@tanstack/react-query';
import { useRouter } from 'next/navigation';
import { apiClient, ApiClientError } from '@/lib/apiClient';
import type { User } from './types';

export function useUser(): UseQueryResult<User, ApiClientError> {
  const router = useRouter();

  return useQuery({
    queryKey: ['user', 'me'],
    queryFn: async (): Promise<User> => {
      const response = await apiClient.get<{ data: User; meta: Record<string, unknown> }>('/api/v1/auth/me');
      return response.data;
    },
    retry: (failureCount, error) => {
      if (error.status === 401) {
        localStorage.removeItem('token');
        localStorage.removeItem('refresh_token');
        localStorage.removeItem('user');
        router.push('/auth/login?redirect=/dashboard');
        return false;
      }
      return failureCount < 2;
    },
    staleTime: 5 * 60 * 1000,
  });
}
