'use client'

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

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

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

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

  return useMutation({
    mutationFn: ({
      identityId,
      ...payload
    }: CreateIdentityPayload & { identityId: string }) =>
      apiClient.put<ApiIdentity>(`/mail/identities/${identityId}`, payload),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['identities'] })
      queryClient.invalidateQueries({ queryKey: ['mail-signatures'] })
    },
  })
}

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

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