'use client'

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

const SIGNATURES_KEY = ['mail-signatures'] as const

async function fetchSignatures(): Promise<ApiMailSignature[]> {
  const res = await apiClient.get<ApiMailSignature[] | { signatures: ApiMailSignature[] }>(
    '/mail/signatures'
  )
  return Array.isArray(res) ? res : (res.signatures ?? [])
}

export function useMailSignatures() {
  const { ready, authenticated } = useAuthReady()

  return useQuery({
    queryKey: SIGNATURES_KEY,
    queryFn: fetchSignatures,
    staleTime: 5 * 60_000,
    enabled: ready && authenticated,
  })
}

export function useCreateMailSignature() {
  const queryClient = useQueryClient()
  return useMutation({
    mutationFn: (payload: CreateMailSignaturePayload) =>
      apiClient.post<{ id: string }>('/mail/signatures', payload),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: SIGNATURES_KEY })
    },
  })
}

export function useUpdateMailSignature() {
  const queryClient = useQueryClient()
  return useMutation({
    mutationFn: ({
      signatureId,
      ...payload
    }: CreateMailSignaturePayload & { signatureId: string }) =>
      apiClient.put(`/mail/signatures/${signatureId}`, payload),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: SIGNATURES_KEY })
      queryClient.invalidateQueries({ queryKey: ['identities'] })
    },
  })
}

export function useDeleteMailSignature() {
  const queryClient = useQueryClient()
  return useMutation({
    mutationFn: (signatureId: string) =>
      apiClient.delete(`/mail/signatures/${signatureId}`),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: SIGNATURES_KEY })
      queryClient.invalidateQueries({ queryKey: ['identities'] })
    },
  })
}
