/**
 * User React Query hooks
 */
import { useMutation, useQuery, useQueryClient, UseQueryOptions, UseMutationOptions } from '@tanstack/react-query';
import { userService } from '../services/user';
import { UserResponse, UserUpdate } from '../types/auth';
import { AdminDeleteRequest, AdminDeleteResponse } from '../types/user';
import { ApiError } from '../client';

// Query Keys
export const userKeys = {
  all: ['user'] as const,
  current: () => [...userKeys.all, 'current'] as const,
  detail: (id: string) => [...userKeys.all, 'detail', id] as const,
  activity: (id: string) => [...userKeys.all, 'activity', id] as const,
  admin: {
    all: () => [...userKeys.all, 'admin'] as const,
    list: () => [...userKeys.admin.all(), 'list'] as const,
    detail: (id: string) => [...userKeys.admin.all(), 'detail', id] as const,
  },
} as const;

// Queries
export const useCurrentUser = (
  options?: Omit<UseQueryOptions<UserResponse, ApiError>, 'queryKey' | 'queryFn'>
) => {
  return useQuery<UserResponse, ApiError>({
    queryKey: userKeys.current(),
    queryFn: () => userService.getCurrentUser(),
    staleTime: 5 * 60 * 1000, // 5 minutes
    ...options,
  });
};

export const useUserActivity = (
  userId: string,
  options?: Omit<UseQueryOptions<any, ApiError>, 'queryKey' | 'queryFn'>
) => {
  return useQuery<any, ApiError>({
    queryKey: userKeys.activity(userId),
    queryFn: () => userService.getUserActivity(userId),
    enabled: !!userId,
    staleTime: 1 * 60 * 1000, // 1 minute for activity data
    ...options,
  });
};

export const useAllUsers = (
  options?: Omit<UseQueryOptions<UserResponse[], ApiError>, 'queryKey' | 'queryFn'>
) => {
  return useQuery<UserResponse[], ApiError>({
    queryKey: userKeys.admin.list(),
    queryFn: () => userService.getAllUsers(),
    staleTime: 2 * 60 * 1000, // 2 minutes
    ...options,
  });
};

export const useUserById = (
  userId: string,
  options?: Omit<UseQueryOptions<UserResponse, ApiError>, 'queryKey' | 'queryFn'>
) => {
  return useQuery<UserResponse, ApiError>({
    queryKey: userKeys.admin.detail(userId),
    queryFn: () => userService.getUserById(userId),
    enabled: !!userId,
    staleTime: 5 * 60 * 1000, // 5 minutes
    ...options,
  });
};

// Mutations
export const useUpdateUser = (
  options?: UseMutationOptions<UserResponse, ApiError, { userId: string; updateData: UserUpdate }>
) => {
  const queryClient = useQueryClient();
  
  return useMutation<UserResponse, ApiError, { userId: string; updateData: UserUpdate }>({
    mutationFn: ({ userId, updateData }) => userService.updateUser(userId, updateData),
    onSuccess: (data, { userId }) => {
      // Update user cache
      queryClient.setQueryData(userKeys.detail(userId), data);
      queryClient.setQueryData(userKeys.current(), data);
      queryClient.setQueryData(userKeys.admin.detail(userId), data);
      // Invalidate user lists
      queryClient.invalidateQueries({ queryKey: userKeys.admin.list() });
    },
    ...options,
  });
};

export const useDeleteUser = (
  options?: UseMutationOptions<{ message: string }, ApiError, string>
) => {
  const queryClient = useQueryClient();
  
  return useMutation<{ message: string }, ApiError, string>({
    mutationFn: (userId: string) => userService.deleteUser(userId),
    onSuccess: (data, userId) => {
      // Remove from cache
      queryClient.removeQueries({ queryKey: userKeys.detail(userId) });
      queryClient.removeQueries({ queryKey: userKeys.admin.detail(userId) });
      // Invalidate user lists
      queryClient.invalidateQueries({ queryKey: userKeys.admin.list() });
    },
    ...options,
  });
};

export const useAdminDeleteUser = (
  options?: UseMutationOptions<AdminDeleteResponse, ApiError, AdminDeleteRequest>
) => {
  const queryClient = useQueryClient();
  
  return useMutation<AdminDeleteResponse, ApiError, AdminDeleteRequest>({
    mutationFn: (deleteRequest: AdminDeleteRequest) => userService.adminDeleteUser(deleteRequest),
    onSuccess: (data, request) => {
      // Remove from cache
      queryClient.removeQueries({ queryKey: userKeys.detail(request.user_id) });
      queryClient.removeQueries({ queryKey: userKeys.admin.detail(request.user_id) });
      // Invalidate user lists
      queryClient.invalidateQueries({ queryKey: userKeys.admin.list() });
    },
    ...options,
  });
};
