import { pb } from "@/lib/pocketbase";
import { type AnyDocument, type DocumentId } from "@/lib/types";
import type { RecordModel } from "pocketbase";
import type { ReactNode } from "react";
import { useEffect } from "react";
import { useDocumentCache } from "./hooks";

/**
 * Provider for the record cache context. Provides a singleton RecordCache instance to children.
 */
export function DocumentLoader({
  documentId,
  children,
}: {
  documentId: DocumentId;
  children: ReactNode;
}) {
  const { dispatch } = useDocumentCache();

  useEffect(() => {
    async function fetchDocumentAndRelations() {
      dispatch({
        type: "loadingDocument",
        docId: documentId,
      });
      const doc: AnyDocument = await pb
        .collection("documents")
        .getOne(documentId, {
          expand:
            "relationships_via_primary,relationships_via_primary.secondary",
        });

      dispatch({
        type: "setDocumentTree",
        doc,
        relationships: doc.expand?.relationships_via_primary || [],
        relatedDocuments:
          doc.expand?.relationships_via_primary?.flatMap(
            (r: RecordModel): AnyDocument[] =>
              // Note: If there are no entries in the expanded secondaries there
              // just won't be an entry instead of an empty list.
              r.expand?.secondary ?? [],
          ) ?? [],
      });
    }

    fetchDocumentAndRelations();
  }, [documentId]);

  return children;
}
