import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
import * as api from '../lib/api';

export function useLogin() {
  const queryClient = useQueryClient();
  
  return useMutation({
    mutationFn: ({ username, password }: { username: string; password: string }) =>
      api.login({ username, password }),
    onSuccess: (data) => {
      queryClient.setQueryData(['auth', 'user'], data.user);
      queryClient.setQueryData(['auth', 'token'], data.access_token);
    },
  });
}

export function useRegister() {
  const queryClient = useQueryClient();
  
  return useMutation({
    mutationFn: ({ username, email, password }: { username: string; email: string; password: string }) =>
      api.register({ username, email, password }),
    onSuccess: (data) => {
      queryClient.setQueryData(['auth', 'user'], data.user);
      queryClient.setQueryData(['auth', 'token'], data.access_token);
    },
  });
}

export function useProfile() {
  return useQuery({
    queryKey: ['auth', 'user'],
    queryFn: api.getProfile,
    enabled: false, // We'll manually trigger this when needed
    retry: false,
  });
}

export function useLogout() {
  const queryClient = useQueryClient();
  
  return useMutation({
    mutationFn: api.logout,
    onSuccess: () => {
      queryClient.removeQueries({ queryKey: ['auth'] });
      queryClient.clear();
    },
  });
}