"use client"

import { useMutation, useQueryClient } from "@tanstack/react-query"
import {
  createPublicShareFolder,
  deletePublicShareItem,
  renamePublicShareItem,
  uploadPublicShareFile,
} from "@/lib/api/public-share-mutations"
import type { useDriveMutations } from "@/lib/api/hooks/use-drive-queries"

export function usePublicShareMutations(token: string, password?: string) {
  const qc = useQueryClient()
  const invalidate = () => qc.invalidateQueries({ queryKey: ["public-share", token] })

  const createFolder = useMutation({
    mutationFn: (path: string) => createPublicShareFolder(token, path, password),
    onSuccess: invalidate,
  })
  const deleteFile = useMutation({
    mutationFn: (path: string) => deletePublicShareItem(token, path, password),
    onSuccess: invalidate,
  })
  const rename = useMutation({
    mutationFn: (body: { path: string; new_name: string }) =>
      renamePublicShareItem(token, body.path, body.new_name, password),
    onSuccess: invalidate,
  })
  const upload = useMutation({
    mutationFn: ({ targetPath, file }: { targetPath: string; file: File }) =>
      uploadPublicShareFile(token, targetPath, file, password),
    onSuccess: invalidate,
  })

  return {
    createFolder,
    deleteFile,
    rename,
    uploadFile: async (targetPath: string, file: File) => {
      await upload.mutateAsync({ targetPath, file })
    },
  }
}

/** Drive-compatible mutations for context menus on public shares. */
export function usePublicShareMenuMutations(
  token: string,
  password?: string
): ReturnType<typeof useDriveMutations> {
  const qc = useQueryClient()
  const base = usePublicShareMutations(token, password)
  const noop = useMutation({ mutationFn: async () => {} })

  return {
    createFolder: base.createFolder,
    deleteFile: base.deleteFile,
    rename: base.rename,
    move: noop,
    copy: noop,
    favorite: noop,
    restore: noop,
    deleteTrash: noop,
    emptyTrash: noop,
    createShare: noop,
    deleteShare: noop,
    lookupShareRecipient: noop,
    createFile: noop,
    invalidate: () => qc.invalidateQueries({ queryKey: ["public-share", token] }),
  } as ReturnType<typeof useDriveMutations>
}
