// Shared session/logout contract used by both the manual "Logout" buttons
// and the automatic inactivity logout (see hooks/useInactivityLogout.js).
// Keeping this in one place means every logout path clears the same things
// the same way, instead of each caller hand-rolling its own localStorage cleanup.

export const ACTIVITY_STORAGE_KEY = 'lastActivityTime';
export const SESSION_START_STORAGE_KEY = 'sessionStartTime';
export const AUTH_PRESENCE_KEY = 'authname';
export const INACTIVITY_TIMEOUT_MS = 60 * 60 * 1000; // 1 hour, resets on user activity
export const ABSOLUTE_SESSION_TIMEOUT_MS = 60 * 60 * 1000; // 1 hour, hard cap since login regardless of activity

export const markActivity = () => {
  localStorage.setItem(ACTIVITY_STORAGE_KEY, String(Date.now()));
};

// Called once at login to start the absolute-lifetime clock for the session.
export const markSessionStart = () => {
  localStorage.setItem(SESSION_START_STORAGE_KEY, String(Date.now()));
};

export const isSessionActive = () => Boolean(localStorage.getItem(AUTH_PRESENCE_KEY));

// Wipes local auth state + the in-memory query cache, then hard-navigates to
// /login. A real navigation (not react-router) is deliberate: it throws away
// the entire JS heap (Redux store, component state, any variable holding
// fetched data) so nothing sensitive survives in memory after logout, and it
// prevents the back button from resurrecting a stale authenticated page from
// the render tree.
export const performSessionLogout = ({ queryClient, dispatch, clearFcmToken, logoutUser } = {}) => {
  try {
    queryClient?.clear();
    if (dispatch && clearFcmToken) dispatch(clearFcmToken());
    if (dispatch && logoutUser) dispatch(logoutUser());
  } finally {
    localStorage.clear();
    window.location.replace('/login');
  }
};
