import { Freight } from "@edr/types";

import type { Wagon } from "@/services/wagon.service";

/** Check if a wagon is available for a schedule based on its current yard.
 * A wagon is eligible if:
 * 1. It is available (or pinned to this schedule)
 * 2. It is physically located at the schedule's origin yard
 */
export function wagonMatchesScheduleOrigin(
  wagon: Pick<Wagon, "id" | "status" | "currentYardId">,
  originYardId?: string | null,
  options?: { allowPinned?: boolean },
): boolean {
  if (options?.allowPinned) return true;
  if (wagon.status !== Freight.WagonStatus.Available) return false;
  if (!originYardId) return true;
  return wagon.currentYardId === originYardId;
}

export function filterWagonsForSchedule(
  wagons: Wagon[],
  originYardId?: string | null,
  pinnedWagonIds?: Set<string>,
): Wagon[] {
  return wagons.filter((wagon) => {
    const isPinned = pinnedWagonIds?.has(wagon.id) ?? false;
    return wagonMatchesScheduleOrigin(wagon, originYardId, {
      allowPinned: isPinned,
    });
  });
}
