"use client"

import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query"
import { apiClient } from "@/lib/api/client"
import { useAuthReady } from "@/lib/api/use-auth-ready"
import type { DriveMount, DriveOrgFolder } from "@/lib/api/types"

export function useAdminDriveOrgFolders() {
  const { ready, authenticated } = useAuthReady()
  return useQuery({
    queryKey: ["admin", "drive", "org-folders"],
    enabled: ready && authenticated,
    queryFn: async () => {
      const res = await apiClient.get<{ folders: DriveOrgFolder[] }>("/admin/drive/org-folders")
      return res.folders ?? []
    },
  })
}

export function useAdminDriveOrgFolderMutations() {
  const qc = useQueryClient()
  const invalidate = () => qc.invalidateQueries({ queryKey: ["admin", "drive", "org-folders"] })

  const create = useMutation({
    mutationFn: (body: { org_slug: string; mount_point: string; quota_bytes?: number }) =>
      apiClient.post<DriveOrgFolder>("/admin/drive/org-folders", body),
    onSuccess: invalidate,
  })

  const update = useMutation({
    mutationFn: (args: { id: string; mount_point?: string; quota_bytes?: number }) =>
      apiClient.put<DriveOrgFolder>(`/admin/drive/org-folders/${encodeURIComponent(args.id)}`, {
        mount_point: args.mount_point,
        quota_bytes: args.quota_bytes,
      }),
    onSuccess: invalidate,
  })

  const remove = useMutation({
    mutationFn: (id: string) =>
      apiClient.delete(`/admin/drive/org-folders/${encodeURIComponent(id)}`),
    onSuccess: invalidate,
  })

  const sync = useMutation({
    mutationFn: (org_slugs: string[]) =>
      apiClient.post<{ folders: DriveOrgFolder[] }>("/admin/drive/org-folders/sync", { org_slugs }),
    onSuccess: invalidate,
  })

  return { create, update, remove, sync }
}

export function useAdminDriveOrgMounts() {
  const { ready, authenticated } = useAuthReady()
  return useQuery({
    queryKey: ["admin", "drive", "org-mounts"],
    enabled: ready && authenticated,
    queryFn: async () => {
      const res = await apiClient.get<{ mounts: DriveMount[] }>("/admin/drive/org-mounts")
      return res.mounts ?? []
    },
  })
}

export type AdminOrgWebDAVMountBody = {
  org_slug: string
  display_name: string
  webdav: {
    host: string
    root: string
    user: string
    password: string
    secure: boolean
  }
}

export function useAdminDriveOrgMountMutations() {
  const qc = useQueryClient()
  const invalidate = () => {
    qc.invalidateQueries({ queryKey: ["admin", "drive", "org-mounts"] })
    qc.invalidateQueries({ queryKey: ["drive", "mounts"] })
  }

  const create = useMutation({
    mutationFn: (body: AdminOrgWebDAVMountBody) =>
      apiClient.post<DriveMount>("/admin/drive/org-mounts", body),
    onSuccess: invalidate,
  })

  const remove = useMutation({
    mutationFn: (id: string) =>
      apiClient.delete(`/admin/drive/org-mounts/${encodeURIComponent(id)}`),
    onSuccess: invalidate,
  })

  return { create, remove }
}
