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

/**
 * PATCH /api/mail/interval — Setzt das Scan-Intervall (in Stunden) für eine
 * bestimmte Mail-Connection. Plan-Limits werden serverseitig geprüft.
 */
export function useMailInterval() {
  const [updating, setUpdating] = useState<string | null>(null);
  const [error, setError] = useState<string | null>(null);

  const setInterval = useCallback(
    async (connectionId: string, interval: number) => {
      setUpdating(connectionId);
      setError(null);
      try {
        await apiFetch<{ ok: boolean; interval: number }>(
          "/api/mail/interval",
          {
            method: "PATCH",
            body: { connectionId, interval },
          },
        );
        return { ok: true };
      } catch (e: any) {
        const msg = e?.message ?? "unknown";
        setError(msg);
        return { ok: false, error: msg };
      } finally {
        setUpdating(null);
      }
    },
    [],
  );

  return { setInterval, updating, error };
}
