import { useMutation, useQueryClient } from "@tanstack/react-query";
import { toast } from "sonner";

import { client } from "@/lib/rpc";
import { MemberRole } from "../types";

interface AddMemberData {
  workspaceId: string;
  userId: string;
  role?: MemberRole;
}

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

  const mutation = useMutation({
    mutationFn: async ({ workspaceId, userId, role }: AddMemberData) => {
      const response = await client.api.members.$post({
        json: { workspaceId, userId, role },
      });

      if (!response.ok) {
        const errorData = await response.json() as { error?: string };
        throw new Error(errorData.error || "Failed to add member");
      }

      const { data } = await response.json();
      return data;
    },
    onSuccess: (_, variables) => {
      toast.success("Member added successfully");
      queryClient.invalidateQueries({ queryKey: ["members", variables.workspaceId] });
      queryClient.invalidateQueries({ queryKey: ["available-users", variables.workspaceId] });
    },
    onError: (error) => {
      toast.error(error.message || "Failed to add member");
    },
  });

  return mutation;
}; 