export function createControlPageSessionLoadState({
  phase,
  panelReady = false,
  apiReady = false,
  controlViewReady = false,
  stateBundle = null,
  workflowStatus = null,
  sessionReadiness = null,
  controlView = null,
  error = null,
} = {}) {
  return {
    phase,
    panelReady,
    apiReady,
    controlViewReady,
    stateBundle,
    workflowStatus,
    sessionReadiness,
    controlView,
    error,
  };
}

function getSessionReadiness(stateBundle, workflowStatus) {
  return workflowStatus?.sessionReadiness
    ?? stateBundle?.workflowStatus?.sessionReadiness
    ?? stateBundle?.report?.sessionReadiness
    ?? null;
}

export function loadMachineSessionForControlPageWorkflow({
  getPanelWindow,
  getPanelApi,
  getControlView,
} = {}) {
  if (typeof getPanelWindow !== "function") {
    throw new Error("A panel window getter is required.");
  }
  if (typeof getPanelApi !== "function") {
    throw new Error("A panel API getter is required.");
  }
  if (typeof getControlView !== "function") {
    throw new Error("A control view getter is required.");
  }

  let panelWindow = null;
  let panelApi = null;
  let controlView = null;
  try {
    panelWindow = getPanelWindow();
    panelApi = getPanelApi();
    controlView = getControlView();
  } catch (error) {
    return createControlPageSessionLoadState({
      phase: "error",
      error: error.message,
    });
  }

  if (!panelWindow) {
    return createControlPageSessionLoadState({
      phase: "waiting-panel",
    });
  }

  if (!panelApi) {
    return createControlPageSessionLoadState({
      phase: "waiting-api",
      panelReady: true,
    });
  }

  if (!controlView) {
    const stateBundle = panelApi.getMachineSessionStateBundle?.() ?? null;
    const workflowStatus = panelApi.getMachineSessionWorkflowStatus?.() ?? null;
    return createControlPageSessionLoadState({
      phase: "waiting-session",
      panelReady: true,
      apiReady: true,
      stateBundle,
      workflowStatus,
      sessionReadiness: getSessionReadiness(stateBundle, workflowStatus),
    });
  }

  const stateBundle = panelApi.getMachineSessionStateBundle?.() ?? null;
  const workflowStatus = panelApi.getMachineSessionWorkflowStatus?.() ?? null;
  return createControlPageSessionLoadState({
    phase: "ready",
    panelReady: true,
    apiReady: true,
    controlViewReady: true,
    stateBundle,
    workflowStatus,
    sessionReadiness: getSessionReadiness(stateBundle, workflowStatus),
    controlView,
  });
}
