import storage from './storage'
import { STORAGE_KEYS, DEFAULT_CONFIG } from './constants'

/**
 * 会话管理模块
 */
class Session {
  constructor() {
    this.sessionId = null
    this.startTime = null
    this.lastActiveTime = null
    this.timeout = DEFAULT_CONFIG.session.timeout
    this.isActive = false
  }

  /**
   * 初始化配置
   */
  init(config = {}) {
    this.timeout = config.session?.timeout || this.timeout
    this._loadFromStorage()
  }

  /**
   * 从存储加载会话信息
   */
  _loadFromStorage() {
    this.sessionId = storage.get(STORAGE_KEYS.SESSION_ID)
    this.startTime = storage.get(STORAGE_KEYS.SESSION_START_TIME)
    this.lastActiveTime = storage.get(STORAGE_KEYS.LAST_ACTIVE_TIME)
  }

  /**
   * 保存到存储
   */
  _saveToStorage() {
    storage.set(STORAGE_KEYS.SESSION_ID, this.sessionId)
    storage.set(STORAGE_KEYS.SESSION_START_TIME, this.startTime)
    storage.set(STORAGE_KEYS.LAST_ACTIVE_TIME, this.lastActiveTime)
  }

  /**
   * 生成会话ID
   */
  _generateSessionId() {
    const timestamp = Date.now().toString(36)
    const random = Math.random().toString(36).substring(2, 8)
    return `session_${timestamp}_${random}`
  }

  /**
   * 开始新会话
   */
  start() {
    const now = Date.now()

    // 检查是否需要新会话
    if (this._shouldStartNewSession()) {
      this.sessionId = this._generateSessionId()
      this.startTime = now
      this.isActive = true
      this.lastActiveTime = now
      this._saveToStorage()

      return {
        isNewSession: true,
        sessionId: this.sessionId,
        startTime: this.startTime,
      }
    }

    // 恢复现有会话
    this.isActive = true
    this.lastActiveTime = now
    storage.set(STORAGE_KEYS.LAST_ACTIVE_TIME, now)

    return {
      isNewSession: false,
      sessionId: this.sessionId,
      startTime: this.startTime,
    }
  }

  /**
   * 判断是否需要开始新会话
   */
  _shouldStartNewSession() {
    // 没有现有会话
    if (!this.sessionId) return true

    // 超过会话超时时间
    if (this.lastActiveTime) {
      const elapsed = Date.now() - this.lastActiveTime
      if (elapsed > this.timeout) return true
    }

    return false
  }

  /**
   * 结束会话
   */
  end() {
    if (!this.isActive) return null

    const now = Date.now()
    const duration = this.startTime ? now - this.startTime : 0

    this.isActive = false
    this.lastActiveTime = now
    storage.set(STORAGE_KEYS.LAST_ACTIVE_TIME, now)

    return {
      sessionId: this.sessionId,
      duration: Math.floor(duration / 1000), // 转换为秒
      startTime: this.startTime,
      endTime: now,
    }
  }

  /**
   * 更新活跃时间
   */
  touch() {
    if (!this.isActive) return

    this.lastActiveTime = Date.now()
    storage.set(STORAGE_KEYS.LAST_ACTIVE_TIME, this.lastActiveTime)
  }

  /**
   * 获取会话ID
   */
  getSessionId() {
    return this.sessionId
  }

  /**
   * 获取会话时长（秒）
   */
  getDuration() {
    if (!this.startTime) return 0
    return Math.floor((Date.now() - this.startTime) / 1000)
  }

  /**
   * 获取会话信息
   */
  getInfo() {
    return {
      sessionId: this.sessionId,
      startTime: this.startTime,
      lastActiveTime: this.lastActiveTime,
      duration: this.getDuration(),
      isActive: this.isActive,
    }
  }

  /**
   * 检查会话是否活跃
   */
  isSessionActive() {
    return this.isActive
  }

  /**
   * 重置会话
   */
  reset() {
    this.sessionId = null
    this.startTime = null
    this.lastActiveTime = null
    this.isActive = false

    storage.remove(STORAGE_KEYS.SESSION_ID)
    storage.remove(STORAGE_KEYS.SESSION_START_TIME)
    storage.remove(STORAGE_KEYS.LAST_ACTIVE_TIME)
  }
}

// 导出单例
export default new Session()