/**
 * `useBanTrend` hook.
 *
 * Fetches time-bucketed ban counts for the trend chart.
 * Re-fetches automatically when `timeRange` or `origin` changes.
 */

import { useCallback, useState } from "react";
import { fetchBanTrend } from "../api/dashboard";
import { useListData } from "./useListData";
import type { BanTrendBucket, BanOriginFilter, TimeRange, BanTrendResponse } from "../types/ban";
import type { FetchError } from "../types/api";

/** Return value shape for {@link useBanTrend}. */
export interface UseBanTrendResult {
  /** Ordered list of time buckets with ban counts. */
  buckets: BanTrendBucket[];
  /** Human-readable bucket size label, e.g. `"1h"`. */
  bucketSize: string;
  /** True while a fetch is in flight. */
  loading: boolean;
  /** Error message or `null`. */
  error: FetchError | null;
  /** Re-fetch the data immediately. */
  reload: () => void;
}

/**
 * Fetch and expose ban trend data for the `BanTrendChart` component.
 *
 * @param timeRange - Time-range preset: `"24h"`, `"7d"`, `"30d"`, or `"365d"`.
 * @param origin    - Origin filter: `"all"`, `"blocklist"`, or `"selfblock"`.
 * @returns Ordered bucket list, bucket-size label, loading state, and error.
 */
export function useBanTrend(
  timeRange: TimeRange,
  origin: BanOriginFilter,
  source: "fail2ban" | "archive" = "fail2ban",
): UseBanTrendResult {
  const [bucketSize, setBucketSize] = useState<string>("1h");

  const fetcher = useCallback(
    (signal: AbortSignal) =>
      fetchBanTrend(timeRange, origin, source, signal),
    [timeRange, origin, source],
  );

  const selector = useCallback((response: BanTrendResponse) => response.buckets, []);

  const onSuccess = useCallback((response: BanTrendResponse) => {
    setBucketSize(response.bucket_size);
  }, []);

  const { items: buckets, loading, error, refresh } = useListData<BanTrendResponse, BanTrendBucket>({
    fetcher,
    selector,
    errorMessage: "Failed to fetch trend data",
    onSuccess,
  });

  return { buckets, bucketSize, loading, error, reload: refresh };
}
