"use client"; /** * Workspace-level queries/mutations (TanStack Query owns server state). */ import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query"; import { workspaceApi } from "@/lib/api"; import type { Workspace, WorkspaceRole } from "@/lib/types"; export function useWorkspaces() { return useQuery({ queryKey: ["workspaces"], queryFn: () => workspaceApi.list() }); } /** * Load a workspace by id or slug (the [workspace] route param accepts both). * * The magic alias `default` (the middleware + post-login redirect target) is * a routing placeholder, NOT a workspace id/slug — no workspace has it, so * `GET /workspaces/default` always 404s. The `[workspace]` index page owns * resolving it (list → first workspace → redirect); the hook must NOT fire * the doomed fetch or the layout's error gate (`isError`) blanks the whole * shell (content + menu) before the page can resolve the alias. A disabled * query reports neither data nor error, so `isError` stays false. */ export function useWorkspace(slugOrId: string) { return useQuery({ queryKey: ["workspaces", slugOrId], queryFn: () => workspaceApi.get(slugOrId), enabled: slugOrId.length > 0 && slugOrId !== "default" }); } export function useWorkspaceMembers(workspaceId: string) { return useQuery({ queryKey: ["workspaces", workspaceId, "members"], queryFn: () => workspaceApi.members(workspaceId), enabled: workspaceId.length > 0 }); } export function useCreateWorkspace() { const qc = useQueryClient(); return useMutation({ mutationFn: (input: { name: string; emoji?: string }) => workspaceApi.create(input.name, input.emoji), onSuccess: () => qc.invalidateQueries({ queryKey: ["workspaces"] }) }); } export function useUpdateWorkspace(workspaceId: string) { const qc = useQueryClient(); return useMutation({ mutationFn: (patch: Partial>) => workspaceApi.update(workspaceId, patch), onSuccess: (ws) => { qc.setQueryData(["workspaces", ws.id], ws); qc.invalidateQueries({ queryKey: ["workspaces"] }); } }); } export function useInviteMember(workspaceId: string) { const qc = useQueryClient(); return useMutation({ mutationFn: (input: { email: string; role: WorkspaceRole }) => workspaceApi.invite(workspaceId, input.email, input.role), onSuccess: () => qc.invalidateQueries({ queryKey: ["workspaces", workspaceId, "invites"] }) }); }