import { ASSETS_CHANGED_EVENT, DOCUMENTS_CHANGED_EVENT } from "@/lib/events";
import type { MediaAsset } from "@/types/media";

type SidebarRefreshEventDetail = {
  docId?: string;
  asset?: MediaAsset;
};

export function bindSidebarRefreshEvents(input: {
  target?: EventTarget;
  onAsset?: (asset?: MediaAsset) => void;
  sidebarRefetch: () => void | Promise<unknown>;
  refreshShareSummary: () => void | Promise<unknown>;
  refreshGroupPublicSummary: () => void | Promise<unknown>;
}): () => void {
  const target = input.target ?? window;
  const handler = (event: Event) => {
    const custom = event as CustomEvent<SidebarRefreshEventDetail>;
    if (custom.detail?.asset) {
      input.onAsset?.(custom.detail.asset);
    }
    void input.sidebarRefetch();
    void input.refreshShareSummary();
    void input.refreshGroupPublicSummary();
  };

  target.addEventListener(ASSETS_CHANGED_EVENT, handler);
  target.addEventListener(DOCUMENTS_CHANGED_EVENT, handler);

  return () => {
    target.removeEventListener(ASSETS_CHANGED_EVENT, handler);
    target.removeEventListener(DOCUMENTS_CHANGED_EVENT, handler);
  };
}
