import { apiClient } from "@/lib/api/client"
import type { DriveFileInfo } from "@/lib/api/types"
import { driveFolderHref } from "@/lib/drive/drive-sidebar-tree"
import { shouldOpenMountFileExternally } from "@/lib/drive/cloud-native-open"
import { shouldOpenInOnlyOffice, shouldOpenInRichTextEditor } from "@/lib/drive/drive-preview"
import { buildDriveDocsEditHref, buildDriveEditHref } from "@/lib/drive/drive-url"

/** Normalize user-entered URL for TipTap link marks. */
export function normalizeDocsLinkHref(raw: string): string {
  const trimmed = raw.trim()
  if (!trimmed) return ""
  if (/^(https?:\/\/|mailto:|tel:|\/|#)/i.test(trimmed)) return trimmed
  return `https://${trimmed}`
}

/** Resolve an in-app href for a drive file or folder (for docs hyperlinks). */
export async function resolveDriveItemLinkHref(file: DriveFileInfo): Promise<string> {
  if (file.type === "directory") {
    const view = file.is_shared ? "shared" : "files"
    return driveFolderHref(view, file.path)
  }

  if (shouldOpenMountFileExternally(file) && file.external_url) {
    return file.external_url
  }

  if (shouldOpenInRichTextEditor(file)) {
    let fileId = file.file_id
    if (!fileId) {
      const path = file.path.startsWith("/") ? file.path : `/${file.path}`
      const info = await apiClient.get<DriveFileInfo>(`/drive/files/info${path}`)
      fileId = info.file_id
    }
    if (fileId) return buildDriveDocsEditHref(fileId)
  }

  if (shouldOpenInOnlyOffice(file)) {
    return buildDriveEditHref(file.path)
  }

  return buildDriveEditHref(file.path)
}
