import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
import * as api from '../lib/api';

export function useArticles(params: api.FindArticlesParams = {}) {
  return useQuery({
    queryKey: ['articles', params],
    queryFn: () => api.fetchArticles(params),
  });
}

export function useArticle(slug: string) {
  return useQuery({
    queryKey: ['article', slug],
    queryFn: () => api.fetchArticleBySlug(slug),
    enabled: !!slug,
  });
}

export function useArticleById(id: string) {
  return useQuery({
    queryKey: ['article', id],
    queryFn: () => api.fetchArticleById(id),
    enabled: !!id,
  });
}

export function useCreateArticle() {
  const queryClient = useQueryClient();
  
  return useMutation({
    mutationFn: api.createArticle,
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['articles'] });
    },
  });
}

export function useUpdateArticle() {
  const queryClient = useQueryClient();
  
  return useMutation({
    mutationFn: ({ id, dto }: { id: string; dto: api.UpdateArticleDto }) => 
      api.updateArticle(id, dto),
    onSuccess: (data, variables) => {
      queryClient.invalidateQueries({ queryKey: ['articles'] });
      queryClient.invalidateQueries({ queryKey: ['article', variables.id] });
      queryClient.invalidateQueries({ queryKey: ['article', data.slug] });
    },
  });
}

export function useDeleteArticle() {
  const queryClient = useQueryClient();
  
  return useMutation({
    mutationFn: api.deleteArticle,
    onSuccess: (_, variables) => {
      queryClient.invalidateQueries({ queryKey: ['articles'] });
      // Also invalidate any specific article queries
      queryClient.removeQueries({ queryKey: ['article', variables] });
    },
  });
}

export function useArchiveArticle() {
  const queryClient = useQueryClient();
  
  return useMutation({
    mutationFn: api.archiveArticle,
    onSuccess: (data, variables) => {
      queryClient.invalidateQueries({ queryKey: ['articles'] });
      queryClient.invalidateQueries({ queryKey: ['article', variables] });
      queryClient.invalidateQueries({ queryKey: ['article', data.slug] });
    },
  });
}

export function usePublishArticle() {
  const queryClient = useQueryClient();
  
  return useMutation({
    mutationFn: ({ id, status = 'published' }: { id: string; status?: 'draft' | 'published' }) => 
      api.publishArticle(id, status),
    onSuccess: (data, variables) => {
      queryClient.invalidateQueries({ queryKey: ['articles'] });
      queryClient.invalidateQueries({ queryKey: ['article', variables.id] });
      queryClient.invalidateQueries({ queryKey: ['article', data.slug] });
    },
  });
}
