// [nexus] Phase 11 — pending-gate indicator hook.
//
// Reads the existing approvals API and exposes a minimal "are there any
// gates waiting on the user globally?" summary, intended for the IconRail
// Assistant destination dot overlay. The rename from "approvals" to
// "gates" is display-only — we reuse `approvalsApi` / `queryKeys.approvals`
// without touching the backend.
//
// The IconRail wiring itself lives in a Phase 8 file the controller owns;
// Phase 11 only ships the hook + tests. See the Phase 11 report for the
// exact diff the controller should apply post-Wave.
import { useMemo } from "react";
import { useQuery } from "@tanstack/react-query";
import type { Approval } from "@paperclipai/shared";
import { approvalsApi } from "../api/approvals";
import { queryKeys } from "../lib/queryKeys";

const PENDING_STATUSES: ReadonlySet<Approval["status"]> = new Set([
  "pending",
  "revision_requested",
]);

export interface GateIndicator {
  hasPendingGates: boolean;
  count: number;
  loading: boolean;
  error: Error | null;
}

/** Count how many approvals in the list are awaiting user decision. */
export function countPendingGates(approvals: readonly Approval[] | undefined): number {
  if (!approvals || approvals.length === 0) return 0;
  let count = 0;
  for (const approval of approvals) {
    if (PENDING_STATUSES.has(approval.status)) count += 1;
  }
  return count;
}

/**
 * Returns `{ hasPendingGates, count, loading, error }` for the given company.
 * When `companyId` is null/undefined the query is disabled and the hook
 * returns zeroed values — useful while bootstrapping IconRail before a
 * company is selected.
 */
export function useGateIndicator(companyId: string | null | undefined): GateIndicator {
  const query = useQuery({
    queryKey: queryKeys.approvals.list(companyId ?? "__none__"),
    queryFn: () => approvalsApi.list(companyId!),
    enabled: Boolean(companyId),
  });

  return useMemo<GateIndicator>(() => {
    const count = countPendingGates(query.data);
    return {
      hasPendingGates: count > 0,
      count,
      loading: query.isLoading,
      error: (query.error as Error | null) ?? null,
    };
  }, [query.data, query.isLoading, query.error]);
}
