"use client";

import type { FileTreeRow } from "@/lib/file-tree/types";
import { filterTopLevelDocIds } from "./dnd";

export type FileTreeDeleteTargets = {
  docIds: string[];
  assetIds: string[];
};

export function computeFileTreeDeleteTargets(args: {
  visibleRows: FileTreeRow[];
  selectedRowIds: Set<string>;
  parentById: Map<string, string | null>;
}): FileTreeDeleteTargets {
  const { visibleRows, selectedRowIds, parentById } = args;

  const docCandidates: string[] = [];
  const assetCandidates: string[] = [];
  const assetDocIdByAssetId = new Map<string, string>();

  for (const row of visibleRows) {
    if (!selectedRowIds.has(row.rowId)) continue;

    if (row.kind === "doc" || row.kind === "index") {
      docCandidates.push(row.docId);
      continue;
    }

    if (row.kind === "asset" || row.kind === "asset-folder") {
      assetCandidates.push(row.asset.id);
      assetDocIdByAssetId.set(row.asset.id, row.docId);
    }
  }

  const docIds = filterTopLevelDocIds(docCandidates, parentById);
  const docIdSet = new Set(docIds);

  const seenAssets = new Set<string>();
  const assetIds: string[] = [];
  for (const assetId of assetCandidates) {
    if (seenAssets.has(assetId)) continue;
    seenAssets.add(assetId);
    const docId = assetDocIdByAssetId.get(assetId);
    if (docId && docIdSet.has(docId)) continue;
    assetIds.push(assetId);
  }

  return { docIds, assetIds };
}
