/**
 * Resource Types Management Hooks
 */

import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
import apiClient from '../api/client';
import { ResourceTypeDefinition } from '../types';

/**
 * Hook to fetch resource types for the current business
 */
export const useResourceTypes = () => {
  return useQuery<ResourceTypeDefinition[]>({
    queryKey: ['resourceTypes'],
    queryFn: async () => {
      const { data } = await apiClient.get('/resource-types/');
      return data;
    },
    // Provide default types if API doesn't have them yet
    placeholderData: [
      {
        id: 'default-staff',
        name: 'Staff',
        category: 'STAFF',
        isDefault: true,
      },
      {
        id: 'default-room',
        name: 'Room',
        category: 'OTHER',
        isDefault: true,
      },
      {
        id: 'default-equipment',
        name: 'Equipment',
        category: 'OTHER',
        isDefault: true,
      },
    ] as ResourceTypeDefinition[],
  });
};

/**
 * Hook to create a new resource type
 */
export const useCreateResourceType = () => {
  const queryClient = useQueryClient();

  return useMutation({
    mutationFn: async (newType: Omit<ResourceTypeDefinition, 'id' | 'isDefault'>) => {
      const { data } = await apiClient.post('/resource-types/', newType);
      return data;
    },
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['resourceTypes'] });
    },
  });
};

/**
 * Hook to update a resource type
 */
export const useUpdateResourceType = () => {
  const queryClient = useQueryClient();

  return useMutation({
    mutationFn: async ({ id, updates }: { id: string; updates: Partial<ResourceTypeDefinition> }) => {
      const { data } = await apiClient.patch(`/resource-types/${id}/`, updates);
      return data;
    },
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['resourceTypes'] });
    },
  });
};

/**
 * Hook to delete a resource type
 */
export const useDeleteResourceType = () => {
  const queryClient = useQueryClient();

  return useMutation({
    mutationFn: async (id: string) => {
      await apiClient.delete(`/resource-types/${id}/`);
    },
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['resourceTypes'] });
    },
  });
};
