import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import * as api from "../service/ProjectService";
import { CreateProjectType, UpdateProjectType } from "../types/ProjectTypes";

export const useGetProjectsByWorkspace = (workspaceId: string) => {
  return useQuery({
    queryKey: ["projects", workspaceId],
    queryFn: () => api.getProjectsByWorkspace(workspaceId),
    enabled: !!workspaceId,
  });
};

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

export const useGetProject = (id: string) => {
  return useQuery({
    queryKey: ["project", id],
    queryFn: () => api.getProject(id),
    enabled: !!id,
  });
};

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

  return useMutation({
    mutationFn: (variables: CreateProjectType) => api.createProject(variables),
    onSuccess: (_data, variables) => {
      queryClient.invalidateQueries({
        queryKey: ["projects", variables.workspaceId],
      });
    },
  });
};

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

  return useMutation({
    mutationFn: ({ id, params }: { id: string; params: UpdateProjectType }) => api.updateProject(id, params),
    onSuccess: (_data, variables) => {
      queryClient.invalidateQueries({ queryKey: ["projects"] });
      queryClient.invalidateQueries({
        queryKey: ["project-detail", variables.id],
      });
    },
  });
};

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

  return useMutation({
    mutationFn: ({ id }: { id: string; workspaceId: string }) => api.deleteProject(id),
    onSuccess: (_data, variables) => {
      queryClient.invalidateQueries({
        queryKey: ["projects", variables.workspaceId],
      });
    },
  });
};
