import { type GameLaunchEnvelope } from './gameLaunch'
import { type BackendLaunchResult } from './backendApi'

export function adaptBackendLaunchResultToEnvelope(result: BackendLaunchResult): GameLaunchEnvelope {
  const launchVariantRouteCode = result.launch.variant
    ? (result.launch.variant.routeCode || null)
    : null

  return {
    config: {
      configUrl: result.launch.config.configUrl,
      configLabel: result.launch.config.configLabel,
      configChecksumSha256: result.launch.config.configChecksumSha256 || null,
      releaseId: result.launch.config.releaseId,
      routeCode: result.launch.config.routeCode || null,
    },
    business: {
      source: result.launch.business.source === 'direct-event' ? 'direct-event' : 'custom',
      eventId: result.launch.business.eventId,
      sessionId: result.launch.business.sessionId,
      sessionToken: result.launch.business.sessionToken,
      sessionTokenExpiresAt: result.launch.business.sessionTokenExpiresAt,
    },
    variant: result.launch.variant
      ? {
        variantId: result.launch.variant.id,
        variantName: result.launch.variant.name,
        routeCode: result.launch.variant.routeCode || result.launch.config.routeCode || result.launch.business.routeCode || null,
        assignmentMode: result.launch.variant.assignmentMode || null,
      }
      : (result.launch.config.routeCode || result.launch.business.routeCode)
        ? {
          routeCode: result.launch.config.routeCode || result.launch.business.routeCode || null,
        }
        : null,
    runtime: result.launch.runtime
      ? {
        runtimeBindingId: result.launch.runtime.runtimeBindingId || null,
        placeId: result.launch.runtime.placeId || null,
        placeName: result.launch.runtime.placeName || null,
        mapId: result.launch.runtime.mapId || null,
        mapName: result.launch.runtime.mapName || null,
        tileReleaseId: result.launch.runtime.tileReleaseId || null,
        courseSetId: result.launch.runtime.courseSetId || null,
        courseVariantId: result.launch.runtime.courseVariantId || null,
        routeCode: result.launch.runtime.routeCode || launchVariantRouteCode || result.launch.config.routeCode || result.launch.business.routeCode || null,
      }
      : null,
    presentation: result.launch.presentation
      ? {
        presentationId: result.launch.presentation.presentationId || null,
        templateKey: result.launch.presentation.templateKey || null,
        version: result.launch.presentation.version || null,
      }
      : null,
    contentBundle: result.launch.contentBundle
      ? {
        bundleId: result.launch.contentBundle.bundleId || null,
        bundleType: result.launch.contentBundle.bundleType || null,
        version: result.launch.contentBundle.version || null,
      }
      : null,
  }
}
