import { useCallback, useState } from 'react';
import { apiFetch } from '../lib/api';

export type UseMailDisconnectReturn = {
  disconnect: (connectionId: string) => Promise<{ ok: boolean; error?: string }>;
  disconnecting: boolean;
  error: string | null;
};

/**
 * Kapselt DELETE /api/mail/disconnect für ein einzelnes Konto.
 *
 * Backend erwartet: Body { connectionId } (nicht als URL-Param).
 * Gibt { ok: true } zurück wenn erfolgreich.
 */
export function useMailDisconnect(): UseMailDisconnectReturn {
  const [disconnecting, setDisconnecting] = useState(false);
  const [error, setError] = useState<string | null>(null);

  const disconnect = useCallback(async (connectionId: string) => {
    setDisconnecting(true);
    setError(null);
    try {
      await apiFetch<{ ok: boolean }>('/api/mail/disconnect', {
        method: 'DELETE',
        body: { connectionId },
      });
      return { ok: true };
    } catch (e: any) {
      const msg = e?.message ?? 'Trennen fehlgeschlagen';
      setError(msg);
      return { ok: false, error: msg };
    } finally {
      setDisconnecting(false);
    }
  }, []);

  return { disconnect, disconnecting, error };
}
