import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
import { message } from 'antd';
import { knowledgeApi, CreateArticleParams, UpdateArticleParams } from '../infrastructure/knowledge.api';

export const KNOWLEDGE_QUERY_KEY = 'knowledge-articles';

export function useKnowledgeArticles(category?: string) {
  return useQuery({
    queryKey: [KNOWLEDGE_QUERY_KEY, category],
    queryFn: () => knowledgeApi.getArticles(category),
  });
}

export function useCreateArticle() {
  const queryClient = useQueryClient();

  return useMutation({
    mutationFn: (params: CreateArticleParams) => knowledgeApi.createArticle(params),
    onSuccess: () => {
      message.success('文章创建成功');
      queryClient.invalidateQueries({ queryKey: [KNOWLEDGE_QUERY_KEY] });
    },
  });
}

export function useUpdateArticle() {
  const queryClient = useQueryClient();

  return useMutation({
    mutationFn: (params: UpdateArticleParams) => knowledgeApi.updateArticle(params),
    onSuccess: () => {
      message.success('文章更新成功');
      queryClient.invalidateQueries({ queryKey: [KNOWLEDGE_QUERY_KEY] });
    },
  });
}

export function useDeleteArticle() {
  const queryClient = useQueryClient();

  return useMutation({
    mutationFn: (id: string) => knowledgeApi.deleteArticle(id),
    onSuccess: () => {
      message.success('文章已删除');
      queryClient.invalidateQueries({ queryKey: [KNOWLEDGE_QUERY_KEY] });
    },
  });
}

export function usePublishArticle() {
  const queryClient = useQueryClient();

  return useMutation({
    mutationFn: (id: string) => knowledgeApi.publishArticle(id),
    onSuccess: () => {
      message.success('文章已发布');
      queryClient.invalidateQueries({ queryKey: [KNOWLEDGE_QUERY_KEY] });
    },
  });
}

export function useUploadKnowledgeFile() {
  return useMutation({
    mutationFn: (file: File) => knowledgeApi.uploadFile(file),
    onError: () => {
      message.error('文件上传失败');
    },
  });
}

export function useUnpublishArticle() {
  const queryClient = useQueryClient();

  return useMutation({
    mutationFn: (id: string) => knowledgeApi.unpublishArticle(id),
    onSuccess: () => {
      message.success('文章已取消发布');
      queryClient.invalidateQueries({ queryKey: [KNOWLEDGE_QUERY_KEY] });
    },
  });
}
