import {
  finishSession,
  finishSessionOnUnload,
  revokeCurrentAuthSession
} from '../services/auth.js'

const AUTH_SESSION_ID_KEY = 'x-financial-auth-session-id'
const AUTH_LAST_ACTIVITY_KEY = 'x-financial-auth-last-activity'
const AUTH_ACTIVITY_COUNT_KEY = 'x-financial-auth-activity-count'

function readStoredSessionId() {
  if (typeof window === 'undefined') {
    return ''
  }

  return String(window.sessionStorage.getItem(AUTH_SESSION_ID_KEY) || '').trim()
}

function readLastActivityAt() {
  if (typeof window === 'undefined') {
    return 0
  }

  return Number(window.sessionStorage.getItem(AUTH_LAST_ACTIVITY_KEY) || 0)
}

function readActivityEventCount() {
  if (typeof window === 'undefined') {
    return 0
  }

  const value = Number(window.sessionStorage.getItem(AUTH_ACTIVITY_COUNT_KEY) || 0)
  return Number.isFinite(value) && value > 0 ? Math.round(value) : 0
}

function buildSessionFinishPayload(reason) {
  const lastActivityAt = readLastActivityAt()
  const pagePath = typeof window === 'undefined'
    ? ''
    : `${window.location.pathname}${window.location.search}`

  return {
    reason,
    lastActivityAt: lastActivityAt ? new Date(lastActivityAt).toISOString() : null,
    activityEventCount: readActivityEventCount(),
    pagePath
  }
}

export function persistAuthSessionMetrics(sessionId) {
  if (typeof window === 'undefined') {
    return
  }

  window.sessionStorage.setItem(AUTH_SESSION_ID_KEY, String(sessionId || '').trim())
  window.sessionStorage.setItem(AUTH_ACTIVITY_COUNT_KEY, '0')
}

export function clearAuthSessionMetrics() {
  if (typeof window === 'undefined') {
    return
  }

  window.sessionStorage.removeItem(AUTH_SESSION_ID_KEY)
  window.sessionStorage.removeItem(AUTH_ACTIVITY_COUNT_KEY)
}

export function incrementAuthActivityCount() {
  if (typeof window === 'undefined') {
    return
  }

  window.sessionStorage.setItem(AUTH_ACTIVITY_COUNT_KEY, String(readActivityEventCount() + 1))
}

export function finalizeAuthSession(reason, options = {}) {
  const sessionId = readStoredSessionId()
  if (!sessionId) {
    return
  }

  const payload = buildSessionFinishPayload(reason)
  if (options.unload) {
    finishSessionOnUnload(sessionId, payload)
    return
  }

  finishSession(sessionId, payload).catch((error) => {
    console.warn('Failed to finish auth session:', error)
  })
}

export function finalizeAndRevokeAuthSession(reason) {
  const sessionId = readStoredSessionId()
  return revokeCurrentAuthSession({
    ...buildSessionFinishPayload(reason),
    sessionId
  })
}
