import { useQuery, useMutation, useQueryClient } from "@tanstack/react-query";
import { queryKeys } from "./keys";
import { faqService } from "@/services/faq.service";
import type { FaqCategoryCreateRequest, FaqItemCreateRequest } from "@/types/faq";

export function useFaqCategories(audience?: string) {
  return useQuery({
    queryKey: queryKeys.faqCategories(audience),
    queryFn: () => faqService.listCategories(audience ? { audience } : undefined),
  });
}

export function useFaqItems(params?: { category_id?: number; audience?: string; search?: string }) {
  return useQuery({
    queryKey: queryKeys.faqItems(params),
    queryFn: () => faqService.listItems(params),
  });
}

export function useCreateFaqCategory() {
  const qc = useQueryClient();
  return useMutation({
    mutationFn: (data: FaqCategoryCreateRequest) => faqService.createCategory(data),
    onSuccess: () => {
      qc.invalidateQueries({ queryKey: ["faq", "categories"] });
    },
  });
}

export function useUpdateFaqCategory() {
  const qc = useQueryClient();
  return useMutation({
    mutationFn: ({ id, data }: { id: number; data: Partial<FaqCategoryCreateRequest> }) =>
      faqService.updateCategory(id, data),
    onSuccess: () => {
      qc.invalidateQueries({ queryKey: ["faq", "categories"] });
      qc.invalidateQueries({ queryKey: ["faq", "items"] });
    },
  });
}

export function useDeleteFaqCategory() {
  const qc = useQueryClient();
  return useMutation({
    mutationFn: (id: number) => faqService.deleteCategory(id),
    onSuccess: () => {
      qc.invalidateQueries({ queryKey: ["faq", "categories"] });
      qc.invalidateQueries({ queryKey: ["faq", "items"] });
    },
  });
}

export function useCreateFaqItem() {
  const qc = useQueryClient();
  return useMutation({
    mutationFn: (data: FaqItemCreateRequest) => faqService.createItem(data),
    onSuccess: () => {
      qc.invalidateQueries({ queryKey: ["faq", "items"] });
      qc.invalidateQueries({ queryKey: ["faq", "categories"] });
    },
  });
}

export function useUpdateFaqItem() {
  const qc = useQueryClient();
  return useMutation({
    mutationFn: ({ id, data }: { id: number; data: Partial<FaqItemCreateRequest> }) =>
      faqService.updateItem(id, data),
    onSuccess: () => {
      qc.invalidateQueries({ queryKey: ["faq", "items"] });
      qc.invalidateQueries({ queryKey: ["faq", "categories"] });
    },
  });
}

export function useDeleteFaqItem() {
  const qc = useQueryClient();
  return useMutation({
    mutationFn: (id: number) => faqService.deleteItem(id),
    onSuccess: () => {
      qc.invalidateQueries({ queryKey: ["faq", "items"] });
      qc.invalidateQueries({ queryKey: ["faq", "categories"] });
    },
  });
}
