// A small hook that mirrors the web app's use-backend-stream but for RN.
// Subscribes to the shared BackendWs singleton, seeds via REST on mount and
// on every reconnect, and keeps positions/signals/account/wallet fresh.
import { useEffect, useRef, useState } from "react";
import { api, getBackendWs, Position, Signal, DeltaAccount, WsEvent } from "@/api/client";

export function useBackendStream(enabled = true) {
  const [positions, setPositions] = useState<Position[]>([]);
  const [signals, setSignals] = useState<Signal[]>([]);
  const [account, setAccount] = useState<DeltaAccount | null>(null);
  const [connected, setConnected] = useState(false);
  const wsRef = useRef<ReturnType<typeof getBackendWs> | null>(null);

  const seed = async () => {
    try {
      const [ps, ss, acc] = await Promise.all([
        api.listPositions().catch(() => [] as Position[]),
        api.listSignals("pending").catch(() => [] as Signal[]),
        api.getDeltaAccount().catch(() => null),
      ]);
      setPositions(ps); setSignals(ss); setAccount(acc);
    } catch { /* ignore */ }
  };

  useEffect(() => {
    if (!enabled) return;
    seed();
    const ws = getBackendWs();
    wsRef.current = ws;
    const off = ws.onEvent((e: WsEvent) => {
      setConnected(true);
      if (e.type === "position.update") {
        setPositions((p) => {
          const i = p.findIndex((x) => x._id === e.position._id);
          if (i === -1) return [e.position, ...p];
          const next = p.slice(); next[i] = e.position; return next;
        });
      } else if (e.type === "position.close") {
        setPositions((p) => p.filter((x) => x._id !== e.position_id));
      } else if (e.type === "signal.new") {
        setSignals((s) => [e.signal, ...s.filter((x) => x._id !== e.signal._id)]);
      } else if (e.type === "signal.expired") {
        setSignals((s) => s.filter((x) => x._id !== e.signal_id));
      } else if (e.type === "account.update") {
        setAccount(e.account);
      }
    });
    ws.start();
    const iv = setInterval(seed, 30_000);
    return () => { off(); clearInterval(iv); };
  }, [enabled]);

  return { positions, signals, account, connected, refresh: seed };
}
