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

export interface TemplateSettingValueParams {
  page?: number;
  limit?: number;
  search?: string;
  templateSettingId?: string;
  resourceId?: string;
}

export function useTemplateSettingValues(
  templateSettingId: string,
  params?: TemplateSettingValueParams,
) {
  return useQuery({
    queryKey: ["templateSettingValues", templateSettingId, params],
    queryFn: () =>
      TemplateSettingValueService.getTemplateSettingValues(
        templateSettingId,
        params as Record<string, unknown>,
      ),
    enabled: !!templateSettingId,
  });
}

export function useTemplateSettingValue(id: string) {
  return useQuery({
    queryKey: ["templateSettingValues", id],
    queryFn: () => TemplateSettingValueService.getTemplateSettingValue(id),
    enabled: !!id,
  });
}

export function useTemplates() {
  return useQuery({
    queryKey: ["templates"],
    queryFn: () => TemplateSettingValueService.getTemplates(),
  });
}

export function useTemplateSettings(templateId: string) {
  return useQuery({
    queryKey: ["templateSettings", templateId],
    queryFn: () => TemplateSettingValueService.getTemplateSettings(templateId),
    enabled: !!templateId,
  });
}

export function useResources(resourceTypeId: string) {
  return useQuery({
    queryKey: ["resources", resourceTypeId],
    queryFn: () => TemplateSettingValueService.getResources(resourceTypeId),
    enabled: !!resourceTypeId,
  });
}

export function useResourceTypes() {
  return useQuery({
    queryKey: ["resourceTypes"],
    queryFn: () => TemplateSettingValueService.getResourceTypes(),
  });
}

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

  const createMutation = useMutation({
    mutationFn: (data: any) =>
      TemplateSettingValueService.createTemplateSettingValue(data),
    onSuccess: () => {
      queryClient.invalidateQueries({
        queryKey: ["templateSettingValues"],
      });
    },
  });

  const updateMutation = useMutation({
    mutationFn: ({ id, data }: { id: string; data: any }) =>
      TemplateSettingValueService.updateTemplateSettingValue(id, data),
    onSuccess: () => {
      queryClient.invalidateQueries({
        queryKey: ["templateSettingValues"],
      });
    },
  });

  const deleteMutation = useMutation({
    mutationFn: (id: string) =>
      TemplateSettingValueService.deleteTemplateSettingValue(id),
    onSuccess: () => {
      queryClient.invalidateQueries({
        queryKey: ["templateSettingValues"],
      });
    },
  });

  return {
    create: createMutation,
    update: updateMutation,
    delete: deleteMutation,
  };
}
