/**
 * Users Query Hooks
 *
 * React Query hooks for fetching and caching user data.
 */

import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
import axios from 'axios';
import { queryKeys } from '../../lib/queryClient';
import type { User } from '../../types/entities';

interface UserListParams {
  limit?: number;
  offset?: number;
}

interface UserListResponse {
  rows: User[];
  count: number;
}

/**
 * Fetch list of users
 */
export function useUsersQuery(params?: UserListParams) {
  const query = params
    ? `?limit=${params.limit || 100}&offset=${params.offset || 0}`
    : '';

  return useQuery({
    queryKey: queryKeys.users.list(params),
    queryFn: async (): Promise<User[]> => {
      const response = await axios.get<UserListResponse>(`users${query}`);
      return response.data.rows;
    },
    staleTime: 5 * 60 * 1000,
  });
}

/**
 * Fetch current logged-in user
 */
export function useCurrentUserQuery() {
  return useQuery({
    queryKey: queryKeys.users.current(),
    queryFn: async (): Promise<User> => {
      const response = await axios.get<User>('auth/me');
      return response.data;
    },
    staleTime: 5 * 60 * 1000,
  });
}

/**
 * Fetch single user by ID
 */
export function useUserQuery(userId: string | undefined) {
  return useQuery({
    queryKey: queryKeys.users.detail(userId || ''),
    queryFn: async (): Promise<User> => {
      const response = await axios.get<User>(`users/${userId}`);
      return response.data;
    },
    enabled: !!userId,
    staleTime: 5 * 60 * 1000,
  });
}

/**
 * Update user mutation
 */
export function useUpdateUserMutation() {
  const queryClient = useQueryClient();

  return useMutation({
    mutationFn: async ({
      id,
      data,
    }: {
      id: string;
      data: Partial<User>;
    }): Promise<User> => {
      const response = await axios.put<User>(`users/${id}`, { id, data });
      return response.data;
    },
    onSuccess: (data, variables) => {
      queryClient.setQueryData(queryKeys.users.detail(variables.id), data);
      queryClient.invalidateQueries({ queryKey: queryKeys.users.all });
    },
  });
}

/**
 * Create user mutation
 */
export function useCreateUserMutation() {
  const queryClient = useQueryClient();

  return useMutation({
    mutationFn: async (data: Partial<User>): Promise<User> => {
      const response = await axios.post<User>('users', { data });
      return response.data;
    },
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: queryKeys.users.all });
    },
  });
}

/**
 * Delete user mutation
 */
export function useDeleteUserMutation() {
  const queryClient = useQueryClient();

  return useMutation({
    mutationFn: async (id: string): Promise<void> => {
      await axios.delete(`users/${id}`);
    },
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: queryKeys.users.all });
    },
  });
}

export default useUsersQuery;
