import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import { apiRequest } from "../lib/api-client";
import { useAuthStore } from "../stores/auth.store";

export type Child = {
  id: string;
  name: string;
  color: string;
  householdId: string;
  createdAt: string;
};

export type CreateChildInput = {
  name: string;
  color?: string;
};

export function useChildren() {
  const activeHouseholdId = useAuthStore((s) => s.activeHouseholdId);

  return useQuery({
    queryKey: ["children", activeHouseholdId],
    queryFn: () => apiRequest<{ children: Child[] }>("/api/children"),
    select: (data) => data.children,
    enabled: !!activeHouseholdId,
  });
}

export function useCreateChild() {
  const queryClient = useQueryClient();
  return useMutation({
    mutationFn: (input: CreateChildInput) =>
      apiRequest<{ child: Child }>("/api/children", {
        method: "POST",
        body: JSON.stringify(input),
      }),
    onSuccess: () => {
      void queryClient.invalidateQueries({ queryKey: ["children"] });
    },
  });
}

export function useDeleteChild() {
  const queryClient = useQueryClient();
  return useMutation({
    mutationFn: (id: string) =>
      apiRequest<{ child: Child }>(`/api/children/${id}`, {
        method: "DELETE",
      }),
    onSuccess: () => {
      void queryClient.invalidateQueries({ queryKey: ["children"] });
    },
  });
}
