import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";

import { aiPromptService } from "@/services/ai-prompt.service";
import type { AIPromptCreateInput } from "@/types/ai-prompt";

const KEY_ROOT = ["ai", "prompts"] as const;

export function useAIPromptKeys(params: { search?: string; page?: number; size?: number } = {}) {
  return useQuery({
    queryKey: [...KEY_ROOT, "keys", params] as const,
    queryFn: () => aiPromptService.listKeys(params),
  });
}

export function useAIPromptVersions(key: string | undefined) {
  return useQuery({
    enabled: !!key,
    queryKey: [...KEY_ROOT, "versions", key] as const,
    queryFn: () => aiPromptService.listVersions(key as string),
  });
}

export function useAIPrompt(id: number | undefined) {
  return useQuery({
    enabled: !!id,
    queryKey: [...KEY_ROOT, "detail", id] as const,
    queryFn: () => aiPromptService.get(id as number),
  });
}

export function useCreateAIPrompt() {
  const qc = useQueryClient();
  return useMutation({
    mutationFn: (input: AIPromptCreateInput) => aiPromptService.create(input),
    onSuccess: () => qc.invalidateQueries({ queryKey: KEY_ROOT }),
  });
}

export function useActivateAIPrompt() {
  const qc = useQueryClient();
  return useMutation({
    mutationFn: (id: number) => aiPromptService.activate(id),
    onSuccess: () => qc.invalidateQueries({ queryKey: KEY_ROOT }),
  });
}

export function useRenderAIPrompt() {
  return useMutation({
    mutationFn: ({ id, variables }: { id: number; variables: Record<string, string> }) =>
      aiPromptService.render(id, variables),
  });
}
