import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
import { api } from '@/lib/api';
import { toast } from 'sonner';

/**
 * Hook to manage module-specific settings
 * 
 * @param moduleId - The module ID
 * @returns Settings data and mutation functions
 */
export function useModuleSettings(moduleId: string) {
  const queryClient = useQueryClient();
  
  const { data: settings, isLoading } = useQuery({
    queryKey: ['module-settings', moduleId],
    queryFn: async () => {
      const response = await api.get(`/modules/${moduleId}/settings`);
      return response as Record<string, any>;
    },
    enabled: !!moduleId,
  });
  
  const updateSettings = useMutation({
    mutationFn: async (newSettings: Record<string, any>) => {
      return api.post(`/modules/${moduleId}/settings`, newSettings);
    },
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['module-settings', moduleId] });
      toast.success('Settings saved successfully');
    },
    onError: (error: any) => {
      const message = error?.response?.data?.message || 'Failed to save settings';
      toast.error(message);
    },
  });
  
  return {
    settings: settings || {},
    isLoading,
    updateSettings,
    saveSetting: (key: string, value: any) => {
      updateSettings.mutate({ ...settings, [key]: value });
    },
  };
}
