/**
 * Session Management - Auto-logout and session tracking
 */

import { SECURITY } from './constants'

export interface SessionData {
  startTime: number
  lastActivity: number
  address: string
}

const SESSION_KEY = 'admin_session'

export function startSession(address: string): void {
  if (typeof window === 'undefined') return

  const session: SessionData = {
    startTime: Date.now(),
    lastActivity: Date.now(),
    address,
  }
  sessionStorage.setItem(SESSION_KEY, JSON.stringify(session))
}

export function updateActivity(): void {
  if (typeof window === 'undefined') return

  const stored = sessionStorage.getItem(SESSION_KEY)
  if (stored) {
    const session: SessionData = JSON.parse(stored)
    session.lastActivity = Date.now()
    sessionStorage.setItem(SESSION_KEY, JSON.stringify(session))
  }
}

export function getSession(): SessionData | null {
  if (typeof window === 'undefined') return null

  const stored = sessionStorage.getItem(SESSION_KEY)
  if (!stored) return null

  try {
    return JSON.parse(stored)
  } catch {
    return null
  }
}

export function isSessionValid(): boolean {
  const session = getSession()
  if (!session) return false

  const timeSinceActivity = Date.now() - session.lastActivity
  return timeSinceActivity < SECURITY.SESSION_TIMEOUT_MS
}

export function endSession(): void {
  if (typeof window === 'undefined') return
  sessionStorage.removeItem(SESSION_KEY)
}

export function getSessionTimeRemaining(): number {
  const session = getSession()
  if (!session) return 0

  const timeSinceActivity = Date.now() - session.lastActivity
  return Math.max(0, SECURITY.SESSION_TIMEOUT_MS - timeSinceActivity)
}

// Auto-update activity on user interaction
if (typeof window !== 'undefined') {
  const events = ['mousedown', 'keydown', 'scroll', 'touchstart']
  events.forEach((event) => {
    window.addEventListener(event, updateActivity, { passive: true })
  })
}
