import { completeTravelSession, loadTravelSession, saveTravelSession, type TravelSession } from "../r3f/navigation/travelSession";
import { applySliceEvent, loadGameSliceSession, saveGameSliceSession, withGameSliceSession } from "./gameSliceState";
import type { GameSliceSession } from "./types";

export function preserveSliceSession(url: string, sliceSessionId: string | null): string {
  return sliceSessionId ? withGameSliceSession(url, sliceSessionId) : url;
}

export function linkSliceTravelSession(slice: GameSliceSession, travelSession: TravelSession): GameSliceSession {
  return { ...slice, activeTravelSessionId: travelSession.id, currentSystemId: travelSession.status === "in_transit" ? travelSession.currentSystemId : slice.currentSystemId };
}

export function syncSliceFromTravelArrival(sliceSessionId: string | null, travelSession: TravelSession): GameSliceSession | null {
  if (!sliceSessionId || travelSession.status !== "arrived") return null;
  const slice = loadGameSliceSession(sliceSessionId);
  if (!slice) return null;
  const poi = travelSession.destinationPoi;
  const next = poi
    ? applySliceEvent({ ...slice, activeTravelSessionId: travelSession.id }, {
        type: "navigation.arrived",
        systemId: poi.systemId,
        poiId: poi.poiId,
        poiName: poi.poiName,
      })
    : { ...slice, currentSystemId: travelSession.currentSystemId, activeTravelSessionId: travelSession.id };
  saveGameSliceSession(next);
  return next;
}

export function resolveSliceTravelCurrentSystem(slice: GameSliceSession, travelSession: TravelSession | null): string {
  if (travelSession?.status === "in_transit") return travelSession.currentSystemId;
  return slice.currentSystemId;
}

export function recoverArrivedTravelSession(navSessionId: string | null) {
  if (!navSessionId) return null;
  const session = loadTravelSession(navSessionId);
  if (!session) return null;
  const arrived = session.status === "arrived" ? session : completeTravelSession(session);
  saveTravelSession(arrived);
  return arrived;
}
