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

export type MonthStatus = {
  id: string;
  householdId: string;
  month: string;
  status: "open" | "closed";
  closedAt: string | null;
  closedBy: string | null;
  finalAmount: number | null;
  notes: string | null;
  finalTransferId: string | null;
  createdAt: string;
};

export function useMonthStatus(month: string) {
  const activeHouseholdId = useAuthStore((s) => s.activeHouseholdId);
  return useQuery({
    queryKey: ["month-status", activeHouseholdId, month],
    queryFn: () =>
      apiRequest<{ status: MonthStatus }>(`/api/months/${month}/status`),
    select: (data) => data.status,
    enabled: !!activeHouseholdId,
  });
}

export type CloseMonthInput = {
  finalAmount: number;
  toUserId: string;
  notes?: string;
};

export function useCloseMonth(month: string) {
  const queryClient = useQueryClient();
  const activeHouseholdId = useAuthStore((s) => s.activeHouseholdId);
  return useMutation({
    mutationFn: (input: CloseMonthInput) =>
      apiRequest<{ status: MonthStatus }>(`/api/months/${month}/close`, {
        method: "POST",
        body: JSON.stringify(input),
      }),
    onSuccess: () => {
      void queryClient.invalidateQueries({ queryKey: ["month-status", activeHouseholdId, month] });
      void queryClient.invalidateQueries({ queryKey: ["settlement-v2", activeHouseholdId, month] });
      void queryClient.invalidateQueries({ queryKey: ["transactions", activeHouseholdId] });
    },
  });
}
