import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query';
import {
  createTemplate,
  deleteTemplate,
  getTemplate,
  listTemplates,
  updateTemplate,
} from '@/api/templates';
import type { SimulationTemplateCreateInput, SimulationTemplatePatchInput } from '@/api/types';

function templatesKey() {
  return ['templates'] as const;
}

function templateKey(id: number) {
  return ['templates', id] as const;
}

export function useTemplates() {
  return useQuery({
    queryKey: templatesKey(),
    queryFn: listTemplates,
  });
}

export function useTemplate(id: number | undefined) {
  return useQuery({
    queryKey: id ? templateKey(id) : ['templates', 'none'],
    queryFn: () => getTemplate(id as number),
    enabled: typeof id === 'number' && !Number.isNaN(id),
  });
}

export function useCreateTemplate() {
  const qc = useQueryClient();
  return useMutation({
    mutationFn: (input: SimulationTemplateCreateInput) => createTemplate(input),
    onSuccess: () => qc.invalidateQueries({ queryKey: templatesKey() }),
  });
}

export function useUpdateTemplate(id: number) {
  const qc = useQueryClient();
  return useMutation({
    mutationFn: (patch: SimulationTemplatePatchInput) => updateTemplate(id, patch),
    onSuccess: () => {
      qc.invalidateQueries({ queryKey: templateKey(id) });
      qc.invalidateQueries({ queryKey: templatesKey() });
    },
  });
}

export function useDeleteTemplate() {
  const qc = useQueryClient();
  return useMutation({
    mutationFn: (id: number) => deleteTemplate(id),
    onSuccess: (_data, id) => {
      qc.invalidateQueries({ queryKey: templateKey(id) });
      qc.invalidateQueries({ queryKey: templatesKey() });
    },
  });
}
