'use client'

import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query'
import { apiClient } from '../client'
import { useAuthReady } from '../use-auth-ready'
import type { ApiMailSettings } from '../types'

export function useMailSettings(enabledOverride?: boolean) {
  const { ready, authenticated } = useAuthReady()
  const enabled = enabledOverride ?? authenticated

  return useQuery({
    queryKey: ['mail-settings'],
    queryFn: () => apiClient.get<ApiMailSettings>('/mail/settings'),
    staleTime: 5 * 60_000,
    enabled: ready && enabled && authenticated,
    retry: 1,
  })
}

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

  return useMutation({
    mutationFn: (patch: Partial<ApiMailSettings>) =>
      apiClient.patch<ApiMailSettings>('/mail/settings', patch),
    onSuccess: (data) => {
      queryClient.setQueryData(['mail-settings'], data)
    },
  })
}
