import type { DriveView } from "@/lib/drive/drive-url"
import {
  buildDriveFolderHref,
  decodePathSegment,
  folderPathFromSegments,
} from "@/lib/drive/drive-url"

export function normalizeDriveFolderPath(path: string): string {
  if (!path || path === "/") return "/"
  return "/" + path.replace(/^\/+/, "").replace(/\/+$/, "")
}

export function driveFolderHref(
  view: DriveView,
  folderPath: string,
  rootId?: string | null,
  routeRoot = "drive"
): string {
  const normalized = normalizeDriveFolderPath(folderPath)
  const segments =
    normalized === "/"
      ? []
      : normalized
          .slice(1)
          .split("/")
          .map(decodePathSegment)

  const hrefView =
    view === "shared" || view === "org" || view === "mount" || view === "files"
      ? view
      : "files"

  return buildDriveFolderHref(hrefView, segments, rootId ?? undefined, routeRoot)
}

export function ancestorFolderPaths(folderPath: string): string[] {
  const normalized = normalizeDriveFolderPath(folderPath)
  if (normalized === "/") return ["/"]
  const parts = normalized.slice(1).split("/")
  const out: string[] = ["/"]
  for (let i = 0; i < parts.length; i++) {
    out.push("/" + parts.slice(0, i + 1).join("/"))
  }
  return out
}

export function selectedFolderPath(view: DriveView, pathSegments: string[]): string {
  if (view === "shared" && pathSegments.length === 0) return "/__shared_root__"
  return folderPathFromSegments(pathSegments)
}

export function isSharedRootSelected(view: DriveView, pathSegments: string[]): boolean {
  return view === "shared" && pathSegments.length === 0
}

export function orgRootKey(folderId: string): string {
  return `/__org__/${folderId}`
}

export function mountRootKey(mountId: string): string {
  return `/__mount__/${mountId}`
}
