import { apiClient } from "@/lib/api/client"
import type { DriveFileInfo } from "@/lib/api/types"
import { stashDriveEditorReturnTo } from "@/lib/drive/drive-editor-return"
import { buildDriveDocsEditHref } from "@/lib/drive/drive-url"
import type { OpenDriveItemRouter } from "@/lib/drive/drive-open-item"

export async function openRichTextDocument(
  file: DriveFileInfo,
  router: OpenDriveItemRouter
) {
  stashDriveEditorReturnTo()
  let fileId = file.file_id
  if (!fileId) {
    const info = await apiClient.get<DriveFileInfo>(
      `/drive/files/info${file.path.startsWith("/") ? file.path : `/${file.path}`}`
    )
    fileId = info.file_id
  }
  if (!fileId) {
    throw new Error("Identifiant du document introuvable")
  }
  router.push(buildDriveDocsEditHref(fileId))
}
