/**
 * Live SignalR hook for the Online Board flight details page.
 *
 * Composes the generic `useLiveFlights` (1E) with TrackerHub's
 * `Subscribe` channel for a single flight. When the server pushes a
 * `Refresh` message, `useLiveFlights` replaces the flight data.
 *
 * 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, IParsedFlightId } from "../types.js";
import { getEnv } from "@/env/index.js";

// ---------------------------------------------------------------------------
// Result type
// ---------------------------------------------------------------------------

export interface UseLiveFlightDetailsResult {
  flight: ISimpleFlight | null;
  connectionStatus: ConnectionStatus;
}

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

export function buildFlightChannelKey(id: IParsedFlightId): string {
  return `flight:${id.carrier}${id.flightNumber}${id.suffix ?? ""}@${id.date}`;
}

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

export function useLiveFlightDetails(
  id: IParsedFlightId,
  initialFlight: ISimpleFlight | null,
): UseLiveFlightDetailsResult {
  const config = useMemo<UseLiveFlightsConfig<IParsedFlightId>>(
    () => ({
      hubUrl: getEnv().SIGNALR_HUB_URL,
      channelKey: buildFlightChannelKey,
    }),
    [],
  );

  // useLiveFlights expects an array — wrap/unwrap the single flight
  const initialData = useMemo(
    () => (initialFlight ? [initialFlight] : []),
    [initialFlight],
  );

  const { data, connectionStatus } = useLiveFlights<
    IParsedFlightId,
    ISimpleFlight
  >(id, initialData, config);

  const flight = data[0] ?? null;

  return { flight, connectionStatus };
}
