import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
import { goodsCategoryClient } from '../api/goodsCategoryClient';
import { GoodsCategory, GoodsCategoryFormData } from '../types/goodsCategory';

// 获取商品分类列表
export const useGoodsCategories = (params?: {
  page?: number;
  pageSize?: number;
  keyword?: string;
  sortBy?: string;
  sortOrder?: 'ASC' | 'DESC';
  filters?: string;
}) => {
  return useQuery({
    queryKey: ['goodsCategories', params],
    queryFn: async () => {
      const response = await goodsCategoryClient.index.$get({
        query: params
      });
      return response.json();
    }
  });
};

// 获取单个商品分类
export const useGoodsCategory = (id: number) => {
  return useQuery({
    queryKey: ['goodsCategory', id],
    queryFn: async () => {
      const response = await goodsCategoryClient[':id'].$get({
        param: { id: id.toString() }
      });
      return response.json();
    },
    enabled: !!id
  });
};

// 创建商品分类
export const useCreateGoodsCategory = () => {
  const queryClient = useQueryClient();

  return useMutation({
    mutationFn: async (data: GoodsCategoryFormData) => {
      const response = await goodsCategoryClient.index.$post({
        json: data
      });
      return response.json();
    },
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['goodsCategories'] });
    }
  });
};

// 更新商品分类
export const useUpdateGoodsCategory = () => {
  const queryClient = useQueryClient();

  return useMutation({
    mutationFn: async ({ id, data }: { id: number; data: GoodsCategoryFormData }) => {
      const response = await goodsCategoryClient[':id'].$put({
        param: { id: id.toString() },
        json: data
      });
      return response.json();
    },
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['goodsCategories'] });
    }
  });
};

// 删除商品分类
export const useDeleteGoodsCategory = () => {
  const queryClient = useQueryClient();

  return useMutation({
    mutationFn: async (id: number) => {
      const response = await goodsCategoryClient[':id'].$delete({
        param: { id: id.toString() }
      });
      return response.json();
    },
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['goodsCategories'] });
    }
  });
};