import { useQuery } from "@tanstack/react-query";
import { supabase } from "@/integrations/supabase/client";

export function useNotificationCount() {
  return useQuery({
    queryKey: ["notification-count"],
    queryFn: async () => {
      const todayIso = new Date(Date.now() - 24 * 3600 * 1000).toISOString();

      const [lowStock, dueCust, lastBackup, pendingOrders, returnedOrders] = await Promise.all([
        supabase
          .from("products")
          .select("id", { count: "exact", head: true })
          .eq("is_deleted", false)
          .lte("stock_quantity", 10),
        supabase
          .from("customers")
          .select("id", { count: "exact", head: true })
          .is("deleted_at", null)
          .gt("total_due", 0),
        supabase
          .from("backups")
          .select("created_at")
          .order("created_at", { ascending: false })
          .limit(1),
        supabase
          .from("sales_orders" as any)
          .select("id", { count: "exact", head: true })
          .in("status", ["pending", "confirmed", "processing", "ready_for_delivery"])
          .gte("created_at", todayIso),
        supabase
          .from("sales_orders" as any)
          .select("id", { count: "exact", head: true })
          .eq("status", "returned")
          .gte("created_at", todayIso),
      ]);

      let backupAlert = 0;
      const lb = lastBackup.data?.[0];
      if (!lb) backupAlert = 1;
      else {
        const ageDays = Math.floor(
          (Date.now() - new Date(lb.created_at).getTime()) / 86400000
        );
        if (ageDays >= 7) backupAlert = 1;
      }

      return (
        (lowStock.count || 0) +
        (dueCust.count || 0) +
        backupAlert +
        (pendingOrders.count || 0) +
        (returnedOrders.count || 0)
      );
    },
    refetchInterval: 60000,
    staleTime: 30000,
  });
}
