'use client'

import { useMutation, useQueryClient } from '@tanstack/react-query'
import { apiClient } from '../client'
import type { CreateMailAccountPayload, UpdateMailAccountPayload } from '../types'

export function useCreateMailAccount() {
  const queryClient = useQueryClient()

  return useMutation({
    mutationFn: (payload: CreateMailAccountPayload) =>
      apiClient.post<{ id: string }>('/mail/accounts', payload),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['accounts'] })
      queryClient.invalidateQueries({ queryKey: ['identities'] })
      queryClient.invalidateQueries({ queryKey: ['mail-signatures'] })
    },
  })
}

export function useUpdateMailAccount(accountId: string) {
  const queryClient = useQueryClient()

  return useMutation({
    mutationFn: (payload: UpdateMailAccountPayload) =>
      apiClient.put<void>(`/mail/accounts/${accountId}`, payload),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['accounts'] })
      queryClient.invalidateQueries({ queryKey: ['mail-account', accountId] })
      queryClient.invalidateQueries({ queryKey: ['identities'] })
    },
  })
}

export function useDeleteMailAccount() {
  const queryClient = useQueryClient()

  return useMutation({
    mutationFn: (accountId: string) =>
      apiClient.delete(`/mail/accounts/${accountId}`),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['accounts'] })
      queryClient.invalidateQueries({ queryKey: ['identities'] })
      queryClient.invalidateQueries({ queryKey: ['mail-signatures'] })
    },
  })
}

export interface ResanitizeBodiesResult {
  scanned: number
  updated: number
}

export function useResanitizeBodies(accountId: string) {
  const queryClient = useQueryClient()

  return useMutation({
    mutationFn: () =>
      apiClient.post<ResanitizeBodiesResult>(
        `/mail/accounts/${accountId}/resanitize-bodies`
      ),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['messages'] })
      queryClient.invalidateQueries({ queryKey: ['thread'] })
    },
  })
}

export function useSyncMailAccount(accountId: string) {
  const queryClient = useQueryClient()

  return useMutation({
    mutationFn: (opts?: { force?: boolean }) =>
      apiClient.post<{ status: string }>(
        `/mail/accounts/${accountId}/sync${opts?.force ? "?force=true" : ""}`
      ),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['accounts'] })
      queryClient.invalidateQueries({ queryKey: ['messages'] })
      queryClient.invalidateQueries({ queryKey: ['thread'] })
    },
  })
}
