// Total count of checks still queued to print, across every money account —
// AP Task 5's Sidebar badge ("Checks to print" with a count when the queue
// is non-empty). There's no single "queue count" endpoint (GET
// /api/c/checks/queue is per-account, server/src/checks.ts), so this is a
// best-effort client-side sum: list the company's money accounts, then ask
// each one's queue length and add them up. Money accounts are few (a
// handful at most for a small business), so the extra round trips are cheap;
// any failure here just means no badge shows, never a broken Sidebar — this
// is a courtesy count, not something anything else depends on.

import { useEffect, useState } from "react";
import { apiGet } from "../lib/api";
import type { ApiAccount } from "../accounts/subtypes";

interface QueueResponse {
  payments: Array<{ paymentId: string }>;
}

export function useChecksQueueCount(companyId: string | null): number {
  const [count, setCount] = useState(0);

  useEffect(() => {
    if (!companyId) {
      setCount(0);
      return;
    }
    let cancelled = false;

    (async () => {
      try {
        const accounts = await apiGet<ApiAccount[]>("/api/c/accounts", companyId);
        const queues = await Promise.all(
          accounts.filter((a) => a.type === "asset").map((a) =>
            apiGet<QueueResponse>(`/api/c/checks/queue?accountId=${a.id}`, companyId).catch(
              () => ({ payments: [] }) as QueueResponse,
            ),
          ),
        );
        if (!cancelled) {
          setCount(queues.reduce((sum, q) => sum + q.payments.length, 0));
        }
      } catch {
        if (!cancelled) setCount(0);
      }
    })();

    return () => {
      cancelled = true;
    };
  }, [companyId]);

  return count;
}
