import { useMemo } from "react";
import type { Particle } from "@/api/types";
import { useLiveParticleChildren } from "@/hooks/use-particle";
import { particlePath, type ParticlePath, parseParticlePath } from "@/lib/particle-path";

type FileParticle = Extract<Particle, { type: "file" }>;

/**
 * Fetches file children (attachments) of a particle in a stream.
 * Uses a one-shot query since attachments are immutable after creation.
 */
export function useParticleAttachments(
  streamPath: ParticlePath,
  particleId: string,
) {
  const childrenPath = useMemo(() => {
    const { networkId, segments } = parseParticlePath(streamPath);
    return particlePath(networkId, [...segments, particleId]);
  }, [streamPath, particleId]);

  const { children, isLoading } = useLiveParticleChildren(childrenPath);

  const attachments = useMemo(
    () => (children ?? []).filter((c): c is FileParticle => c.type === "file"),
    [children],
  );

  return { attachments, isLoading };
}
