aboutsummaryrefslogtreecommitdiff
path: root/apps/web/hooks/use-project-mutations.ts
blob: 3ec241765258e3249d43406b0a602191865a04f8 (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
90
91
92
"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 (input: string | { name: string; emoji?: string }) => {
			const { name, emoji } =
				typeof input === "string" ? { name: input, emoji: undefined } : input

			const response = await $fetch("@post/projects", {
				body: { name, emoji },
			})

			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,
	}
}