import type { AdminRole } from "@xtablo/shared-types";

const ADMIN_SESSION_STORAGE_KEY = "xtablo-admin-session";

export type StoredAdminSession = {
  expiresAt: string;
  operatorEmail: string;
  operatorId: string;
  role: AdminRole;
  sessionToken: string;
};

export function getStoredAdminSession() {
  const rawSession = localStorage.getItem(ADMIN_SESSION_STORAGE_KEY);
  if (!rawSession) {
    return null;
  }

  try {
    const parsedSession = JSON.parse(rawSession) as StoredAdminSession;
    if (new Date(parsedSession.expiresAt).getTime() <= Date.now()) {
      localStorage.removeItem(ADMIN_SESSION_STORAGE_KEY);
      return null;
    }
    return parsedSession;
  } catch {
    localStorage.removeItem(ADMIN_SESSION_STORAGE_KEY);
    return null;
  }
}

export function storeAdminSession(session: StoredAdminSession) {
  localStorage.setItem(ADMIN_SESSION_STORAGE_KEY, JSON.stringify(session));
}

export function clearStoredAdminSession() {
  localStorage.removeItem(ADMIN_SESSION_STORAGE_KEY);
}
