'use client'

import { useMutation } from '@tanstack/react-query'
import { apiClient } from '../client'
import type { MailAccountTestResult } from '../types'

export interface TestMailAccountPayload {
  /** Compte existant : permet de tester sans resaisir le mot de passe */
  account_id?: string
  imap_host: string
  imap_port: number
  imap_tls: boolean
  smtp_host: string
  smtp_port: number
  smtp_tls: boolean
  username?: string
  password?: string
  auth_type?: 'password' | 'oauth2' | string
}

export function useTestMailAccount(existingAccountId?: string) {
  return useMutation({
    mutationFn: (payload: TestMailAccountPayload) => {
      const body: TestMailAccountPayload = existingAccountId
        ? { ...payload, account_id: existingAccountId }
        : payload
      return apiClient.post<MailAccountTestResult>('/mail/accounts/test', body)
    },
  })
}
