"use client"

import { useMutation, useQueryClient, type QueryClient } from "@tanstack/react-query"
import { apiClient } from "../client"
import type { ApiMessageAttachment } from "../map-message-attachments"
import {
  MAIL_DRIVE_DEFAULT_FOLDER,
  normalizeMailDriveFolder,
} from "@/lib/mail/mail-drive"

type SaveToDriveResponse = {
  drive_path: string
}

type SaveAllToDriveResponse = {
  attachments?: ApiMessageAttachment[]
}

export function useSaveAttachmentToDrive(messageId: string) {
  const queryClient = useQueryClient()

  return useMutation({
    mutationFn: async ({
      attachmentId,
      folderPath = MAIL_DRIVE_DEFAULT_FOLDER,
    }: {
      attachmentId: string
      folderPath?: string
    }) => {
      const res = await apiClient.post<SaveToDriveResponse>(
        `/mail/messages/${messageId}/attachments/${attachmentId}/save-to-drive`,
        { folder_path: folderPath }
      )
      return res.drive_path
    },
    onSuccess: (_drivePath, variables) => {
      queryClient.invalidateQueries({ queryKey: ["message-attachments", messageId] })
      invalidateDriveAfterMailSave(queryClient, variables.folderPath)
    },
  })
}

export function useSaveMessageAttachmentsToDrive(messageId: string) {
  const queryClient = useQueryClient()

  return useMutation({
    mutationFn: async (folderPath: string = MAIL_DRIVE_DEFAULT_FOLDER) => {
      const res = await apiClient.post<SaveAllToDriveResponse>(
        `/mail/messages/${messageId}/attachments/save-to-drive`,
        { folder_path: folderPath }
      )
      return res.attachments ?? []
    },
    onSuccess: (_attachments, folderPath) => {
      queryClient.invalidateQueries({ queryKey: ["message-attachments", messageId] })
      invalidateDriveAfterMailSave(queryClient, folderPath)
    },
  })
}

function invalidateDriveAfterMailSave(queryClient: QueryClient, folderPath?: string) {
  queryClient.invalidateQueries({ queryKey: ["drive"] })
  const folder = normalizeMailDriveFolder(folderPath ?? MAIL_DRIVE_DEFAULT_FOLDER)
  queryClient.invalidateQueries({ queryKey: ["drive", "files", folder] })
  queryClient.invalidateQueries({ queryKey: ["drive", "recent"] })
}
