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

export type MailBlockedItem = {
  id: string;
  subject: string;
  sender_email: string;
  sender_name: string | null;
  received_at: string;
  connection_id: string;
};

export type MailResultsResponse = {
  results: MailBlockedItem[];
  total: number;
  page: number;
  pages: number;
};

/**
 * GET /api/mail/results — Liste der in den letzten 24h gelöschten Mails.
 * Backend räumt selbst nach 24h auf (deleteOldMailBlocked).
 */
export function useMailResults(enabled: boolean = true) {
  const [results, setResults] = useState<MailBlockedItem[]>([]);
  const [total, setTotal] = useState(0);
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState<string | null>(null);

  const refresh = useCallback(async () => {
    if (!enabled) return;
    setLoading(true);
    try {
      const res = await apiFetch<MailResultsResponse>(
        "/api/mail/results?page=1",
      );
      setResults(res.results ?? []);
      setTotal(res.total ?? 0);
      setError(null);
    } catch (e: any) {
      setError(e?.message ?? "unknown");
    } finally {
      setLoading(false);
    }
  }, [enabled]);

  useEffect(() => {
    if (enabled) refresh();
  }, [enabled, refresh]);

  return { results, total, loading, error, refresh };
}
