/**
 * Live SignalR hook for Online Board search pages.
 *
 * Composes the generic `useLiveFlights` (1E) with TrackerHub's
 * `SubscribeDate` channel. When the server pushes a `RefreshDate`
 * message, `useLiveFlights` replaces the flight list atomically.
 *
 * Client-only — SSR is handled by `useLiveFlights` internally.
 *
 * @module
 */

import { useMemo } from "react";
import {
  useLiveFlights,
  type UseLiveFlightsConfig,
} from "@/shared/hooks/useLiveFlights.js";
import type { ConnectionStatus } from "@/shared/signalr/connection.js";
import type { ISimpleFlight } from "../types.js";
import { getEnv } from "@/env/index.js";

// ---------------------------------------------------------------------------
// Param & result types
// ---------------------------------------------------------------------------

export interface LiveBoardSearchParams {
  date: string;
  departure?: string;
  arrival?: string;
}

export interface UseLiveBoardSearchResult {
  flights: ISimpleFlight[];
  connectionStatus: ConnectionStatus;
}

// ---------------------------------------------------------------------------
// Channel key builder (exported for testing)
// ---------------------------------------------------------------------------

export function buildBoardChannelKey(params: LiveBoardSearchParams): string {
  return `board:${params.date}:${params.departure ?? ""}:${params.arrival ?? ""}`;
}

// ---------------------------------------------------------------------------
// Hook
// ---------------------------------------------------------------------------

export function useLiveBoardSearch(
  params: LiveBoardSearchParams,
  initialFlights: ISimpleFlight[],
  onRefresh?: () => void,
): UseLiveBoardSearchResult {
  const config = useMemo<UseLiveFlightsConfig<LiveBoardSearchParams>>(
    () => ({
      hubUrl: getEnv().SIGNALR_HUB_URL,
      channelKey: buildBoardChannelKey,
      subscription: {
        eventName: "RefreshDate",
        invokeMethodName: "SubscribeDate",
        args: (p) => [p.date, p.departure, p.arrival],
      },
      onMessage: (message) => {
        if (Array.isArray(message)) return message;
        onRefresh?.();
        return undefined;
      },
    }),
    [onRefresh],
  );

  const { data, connectionStatus } = useLiveFlights<
    LiveBoardSearchParams,
    ISimpleFlight
  >(params, initialFlights, config);

  return { flights: data, connectionStatus };
}
