import { useQuery } from "@tanstack/react-query";
import { supabase } from "@/integrations/supabase/client";
import { SALE_STATUSES, type SaleStatus } from "@/components/sales/sale-status";

// Fallback defaults — used until DB rules load (or if a status is missing from DB)
const FALLBACK: Record<SaleStatus, SaleStatus[]> = {
  pending: ["confirmed", "cancelled"],
  confirmed: ["processing", "cancelled", "pending"],
  processing: ["ready_for_delivery", "completed", "cancelled"],
  ready_for_delivery: ["delivered", "partial_delivered", "cancelled"],
  completed: ["delivered", "partial_delivered", "returned"],
  partial_delivered: ["delivered", "returned"],
  delivered: ["returned"],
  returned: [],
  cancelled: [],
};

export type SaleStatusRules = Record<string, SaleStatus[]>;

export function useSaleStatusRules() {
  const { data, isLoading } = useQuery({
    queryKey: ["sale-status-transitions"],
    queryFn: async (): Promise<SaleStatusRules> => {
      const { data, error } = await supabase
        .from("sale_status_transitions" as any)
        .select("from_status, allowed_to");
      if (error) throw error;
      const map: SaleStatusRules = {};
      for (const row of (data as any[]) || []) {
        map[row.from_status] = (row.allowed_to || []) as SaleStatus[];
      }
      return map;
    },
    staleTime: 60_000,
  });

  const rules: SaleStatusRules = data ?? FALLBACK;

  const getNext = (current: string): SaleStatus[] => {
    if (current in rules) return rules[current] || [];
    return FALLBACK[current as SaleStatus] || [];
  };

  return { rules, getNext, isLoading, allStatuses: SALE_STATUSES };
}

export { FALLBACK as DEFAULT_TRANSITIONS };
