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

export type HouseholdSettings = {
  id: string;
  householdId: string;
  ownerName: string;
  partnerName: string;
  userSharePercent: number;
  monthlyBudget: number;
  currency: string;
  splitChildCosts: boolean;
  payerUserId: string | null;
  onboardingComplete: boolean;
  language: string;
  createdAt: string;
  updatedAt: string;
};

export type UpdateHouseholdSettingsInput = {
  ownerName?: string;
  partnerName?: string;
  userSharePercent?: number;
  monthlyBudget?: number;
  currency?: string;
  splitChildCosts?: boolean;
  payerUserId?: string | null;
  onboardingComplete?: boolean;
  language?: string;
};

export function useHouseholdSettings() {
  const activeHouseholdId = useAuthStore((s) => s.activeHouseholdId);
  return useQuery({
    queryKey: ["household-settings", activeHouseholdId],
    queryFn: () => apiRequest<{ settings: HouseholdSettings }>("/api/household-settings"),
    select: (data) => data.settings,
    enabled: !!activeHouseholdId,
  });
}

export function useUpdateHouseholdSettings() {
  const queryClient = useQueryClient();
  const activeHouseholdId = useAuthStore((s) => s.activeHouseholdId);
  return useMutation({
    mutationFn: (input: UpdateHouseholdSettingsInput) =>
      apiRequest<{ settings: HouseholdSettings }>("/api/household-settings", {
        method: "PATCH",
        body: JSON.stringify(input),
      }),
    onSuccess: () => {
      void queryClient.invalidateQueries({ queryKey: ["household-settings", activeHouseholdId] });
      void queryClient.invalidateQueries({ queryKey: ["netto-month"] });
      void queryClient.invalidateQueries({ queryKey: ["settlement-v2"] });
    },
  });
}
