import { describe, expect, it, vi } from "vitest";
import type { MediaAsset } from "@/types/media";
import { ASSETS_CHANGED_EVENT, DOCUMENTS_CHANGED_EVENT } from "@/lib/events";
import { bindSidebarRefreshEvents } from "./sidebar-events";

function buildAsset(overrides: Partial<MediaAsset> = {}): MediaAsset {
  return {
    id: "asset-1",
    workspace_id: "ws-1",
    document_id: "doc-1",
    asset_type: "image",
    file_url: "/files/a.png",
    thumbnail_url: null,
    bucket: null,
    storage_path: "uploads/a.png",
    file_name: "a.png",
    file_size: 1,
    mime_type: "image/png",
    ocr_payload: undefined,
    ocr_strategy: null,
    ocr_text: null,
    ocr_status: null,
    signed_url: null,
    created_at: "2026-04-21T00:00:00.000Z",
    updated_at: "2026-04-21T00:00:00.000Z",
    ...overrides,
  };
}

describe("bindSidebarRefreshEvents", () => {
  it("收到 documents-changed 时应触发 sidebar 与共享摘要刷新", () => {
    const target = new EventTarget();
    const onAsset = vi.fn();
    const sidebarRefetch = vi.fn();
    const refreshShareSummary = vi.fn();
    const refreshGroupPublicSummary = vi.fn();

    const dispose = bindSidebarRefreshEvents({
      target,
      onAsset,
      sidebarRefetch,
      refreshShareSummary,
      refreshGroupPublicSummary,
    });

    target.dispatchEvent(new CustomEvent(DOCUMENTS_CHANGED_EVENT, { detail: { docId: "doc-1" } }));

    expect(onAsset).not.toHaveBeenCalled();
    expect(sidebarRefetch).toHaveBeenCalledTimes(1);
    expect(refreshShareSummary).toHaveBeenCalledTimes(1);
    expect(refreshGroupPublicSummary).toHaveBeenCalledTimes(1);

    dispose();
  });

  it("收到 assets-changed 且带 asset 时应先透传 asset 再刷新", () => {
    const target = new EventTarget();
    const onAsset = vi.fn();
    const sidebarRefetch = vi.fn();
    const refreshShareSummary = vi.fn();
    const refreshGroupPublicSummary = vi.fn();
    const asset = buildAsset({ asset_type: "mindmap" });

    const dispose = bindSidebarRefreshEvents({
      target,
      onAsset,
      sidebarRefetch,
      refreshShareSummary,
      refreshGroupPublicSummary,
    });

    target.dispatchEvent(new CustomEvent(ASSETS_CHANGED_EVENT, { detail: { docId: "doc-1", asset } }));

    expect(onAsset).toHaveBeenCalledWith(asset);
    expect(sidebarRefetch).toHaveBeenCalledTimes(1);
    expect(refreshShareSummary).toHaveBeenCalledTimes(1);
    expect(refreshGroupPublicSummary).toHaveBeenCalledTimes(1);

    dispose();
  });
});
