import { finishSession } from '../../utils/backendApi'
import { loadBackendAuthTokens, loadBackendBaseUrl } from '../../utils/backendAuth'
import { clearSessionRecoverySnapshot, loadSessionRecoverySnapshot } from '../../game/core/sessionRecovery'
import { getBackendSessionContextFromLaunchEnvelope, prepareMapPageUrlForRecovery } from '../../utils/gameLaunch'

Page({
  onLoad() {
    const recoverySnapshot = loadSessionRecoverySnapshot()
    if (recoverySnapshot) {
      this.promptRecoveryAtEntry()
      return
    }

    this.redirectToDefaultEntry()
  },

  redirectToDefaultEntry() {
    const tokens = loadBackendAuthTokens()
    const url = tokens && tokens.accessToken
      ? '/pages/home/home'
      : '/pages/login/login'
    wx.redirectTo({ url })
  },

  promptRecoveryAtEntry() {
    const recoverySnapshot = loadSessionRecoverySnapshot()
    if (!recoverySnapshot) {
      this.redirectToDefaultEntry()
      return
    }

    wx.showModal({
      title: '恢复对局',
      content: '检测到上次有未正常结束的对局，是否继续恢复？',
      confirmText: '继续恢复',
      cancelText: '放弃',
      success: (result) => {
        if (result.confirm) {
          wx.redirectTo({
            url: prepareMapPageUrlForRecovery(recoverySnapshot.launchEnvelope),
          })
          return
        }

        const sessionContext = getBackendSessionContextFromLaunchEnvelope(recoverySnapshot.launchEnvelope)
        if (!sessionContext) {
          clearSessionRecoverySnapshot()
          wx.showToast({
            title: '已放弃上次对局',
            icon: 'none',
            duration: 1400,
          })
          this.redirectToDefaultEntry()
          return
        }

        finishSession({
          baseUrl: loadBackendBaseUrl(),
          sessionId: sessionContext.sessionId,
          sessionToken: sessionContext.sessionToken,
          status: 'cancelled',
          summary: {},
        })
          .catch(() => {
            // 放弃恢复不阻塞进入业务页；失败只丢给后续状态页处理。
          })
          .finally(() => {
            clearSessionRecoverySnapshot()
            wx.showToast({
              title: '已放弃上次对局',
              icon: 'none',
              duration: 1400,
            })
            this.redirectToDefaultEntry()
          })
      },
    })
  },
})
