aboutsummaryrefslogtreecommitdiff
path: root/apps/web/hooks/use-project-mutations.ts
blob: a6766f4e3ff2e6bc10dd9f5e53511950b0a34e40 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
"use client";

import { $fetch } from "@lib/api";
import { useMutation, useQueryClient } from "@tanstack/react-query";
import { toast } from "sonner";
import { useProject } from "@/stores";

export function useProjectMutations() {
	const queryClient = useQueryClient();
	const { selectedProject, setSelectedProject } = useProject();

	const createProjectMutation = useMutation({
		mutationFn: async (name: string) => {
			const response = await $fetch("@post/projects", {
				body: { name },
			});

			if (response.error) {
				throw new Error(response.error?.message || "Failed to create project");
			}

			return response.data;
		},
		onSuccess: (data) => {
			toast.success("Project created successfully!");
			queryClient.invalidateQueries({ queryKey: ["projects"] });

			// Automatically switch to the newly created project
			if (data?.containerTag) {
				setSelectedProject(data.containerTag);
			}
		},
		onError: (error) => {
			toast.error("Failed to create project", {
				description: error instanceof Error ? error.message : "Unknown error",
			});
		},
	});

	const deleteProjectMutation = useMutation({
		mutationFn: async ({
			projectId,
			action,
			targetProjectId,
		}: {
			projectId: string;
			action: "move" | "delete";
			targetProjectId?: string;
		}) => {
			const response = await $fetch(`@delete/projects/${projectId}`, {
				body: { action, targetProjectId },
			});

			if (response.error) {
				throw new Error(response.error?.message || "Failed to delete project");
			}

			return response.data;
		},
		onSuccess: (_, variables) => {
			toast.success("Project deleted successfully");
			queryClient.invalidateQueries({ queryKey: ["projects"] });

			// If we deleted the selected project, switch to default
			const deletedProject = queryClient
				.getQueryData<any[]>(["projects"])
				?.find((p) => p.id === variables.projectId);
			if (deletedProject?.containerTag === selectedProject) {
				setSelectedProject("sm_project_default");
			}
		},
		onError: (error) => {
			toast.error("Failed to delete project", {
				description: error instanceof Error ? error.message : "Unknown error",
			});
		},
	});

	const switchProject = (containerTag: string) => {
		setSelectedProject(containerTag);
		toast.success("Project switched successfully");
	};

	return {
		createProjectMutation,
		deleteProjectMutation,
		switchProject,
	};
}