import type { DriveMoveSource } from "@/lib/drive/drive-move-items"

export const DRIVE_DND_TYPE = "application/x-ultimail-drive-items"

export type DriveDragItem = Pick<DriveMoveSource, "path" | "name" | "type">

export function setDriveDragData(dataTransfer: DataTransfer, items: DriveDragItem[]): void {
  dataTransfer.setData(DRIVE_DND_TYPE, JSON.stringify(items))
  dataTransfer.setData("text/plain", items.map((item) => item.path).join("\n"))
  dataTransfer.effectAllowed = "move"
}

export function getDriveDragData(dataTransfer: DataTransfer): DriveDragItem[] | null {
  const raw = dataTransfer.getData(DRIVE_DND_TYPE)
  if (!raw) return null
  try {
    const parsed = JSON.parse(raw) as DriveDragItem[]
    if (!Array.isArray(parsed) || parsed.length === 0) return null
    return parsed.filter(
      (item) =>
        item &&
        typeof item.path === "string" &&
        typeof item.name === "string" &&
        (item.type === "file" || item.type === "directory")
    )
  } catch {
    return null
  }
}

export function resolveDragSources(
  file: DriveDragItem,
  selectedPaths: Set<string>,
  allItems: DriveDragItem[]
): DriveDragItem[] {
  if (selectedPaths.has(file.path) && selectedPaths.size > 1) {
    const selected = allItems.filter((item) => selectedPaths.has(item.path))
    if (selected.length > 0) return selected
  }
  return [file]
}
