import type { useDriveMutations } from "@/lib/api/hooks/use-drive-queries"

const API_BASE = process.env.NEXT_PUBLIC_API_URL ?? "/api/v1"

function withPassword(url: string, password?: string) {
  if (!password) return url
  const sep = url.includes("?") ? "&" : "?"
  return `${url}${sep}password=${encodeURIComponent(password)}`
}

function fileApiPath(token: string, filePath: string) {
  const parts = filePath
    .replace(/^\/+/, "")
    .split("/")
    .filter(Boolean)
    .map(encodeURIComponent)
  return `${API_BASE}/drive/public/shares/${encodeURIComponent(token)}/files/${parts.join("/")}`
}

function folderApiPath(token: string, folderPath: string) {
  const parts = folderPath
    .replace(/^\/+/, "")
    .split("/")
    .filter(Boolean)
    .map(encodeURIComponent)
  return `${API_BASE}/drive/public/shares/${encodeURIComponent(token)}/folders/${parts.join("/")}`
}

export async function uploadPublicShareFile(
  token: string,
  targetPath: string,
  file: File,
  password?: string
) {
  const path = targetPath.startsWith("/") ? targetPath : `/${targetPath}`
  const res = await fetch(withPassword(fileApiPath(token, path), password), {
    method: "PUT",
    headers: { "Content-Type": file.type || "application/octet-stream" },
    body: file,
  })
  if (!res.ok) throw new Error("upload_failed")
}

export async function createPublicShareFolder(
  token: string,
  folderPath: string,
  password?: string
) {
  const path = folderPath.startsWith("/") ? folderPath : `/${folderPath}`
  const res = await fetch(withPassword(folderApiPath(token, path), password), {
    method: "POST",
  })
  if (!res.ok) throw new Error("create_folder_failed")
}

export async function deletePublicShareItem(
  token: string,
  filePath: string,
  password?: string
) {
  const path = filePath.startsWith("/") ? filePath : `/${filePath}`
  const res = await fetch(withPassword(fileApiPath(token, path), password), {
    method: "DELETE",
  })
  if (!res.ok) throw new Error("delete_failed")
}

export async function renamePublicShareItem(
  token: string,
  filePath: string,
  newName: string,
  password?: string
) {
  const res = await fetch(withPassword(`${API_BASE}/drive/public/shares/${encodeURIComponent(token)}/rename`, password), {
    method: "POST",
    headers: { "Content-Type": "application/json" },
    body: JSON.stringify({ path: filePath, new_name: newName }),
  })
  if (!res.ok) throw new Error("rename_failed")
}

/** Minimal mutation surface compatible with drive context menus. */
export type PublicShareMutations = Pick<
  ReturnType<typeof useDriveMutations>,
  "deleteFile" | "rename" | "createFolder"
>
