import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import * as api from "../service/WorkspaceService";
import {
  CreateWorkspaceType,
  UpdateWorkspaceType,
} from "../types/WorkspaceTypes";

export const useGetWorkspaces = () => {
  return useQuery({
    queryKey: ["workspaces"],
    queryFn: api.getWorkspacesByUser,
  });
};

export const useGetWorkspaceDetail = (id: string) => {
  return useQuery({
    queryKey: ["workspace-detail", id],
    queryFn: () => api.getWorkspaceDetail(id),
    enabled: !!id,
  });
};

export const useCreateWorkspace = () => {
  const queryClient = useQueryClient();

  return useMutation({
    mutationFn: (variables: CreateWorkspaceType) => api.createWorkspace(variables),
    onSuccess: () => {
      queryClient.invalidateQueries({
        queryKey: ["workspaces"],
      });
    },
  });
};

export const useUpdateWorkspace = () => {
  const queryClient = useQueryClient();

  return useMutation({
    mutationFn: ({
      id,
      params,
    }: {
      id: string;
      params: UpdateWorkspaceType;
    }) => api.updateWorkspace(id, params),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ["workspaces"] });
      queryClient.invalidateQueries({ queryKey: ["workspace-detail"] });
    },
  });
};

export const useDeleteWorkspace = () => {
  const queryClient = useQueryClient();

  return useMutation({
    mutationFn: (id: string) => api.deleteWorkspace(id),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ["workspaces"] });
    },
  });
};
