/**
 * otpSecureStorage.js
 * OTP Testing & Automation Framework — Secure Storage
 *
 * FOR DEV / STAGING / QA / ACCESSIBILITY TESTING ONLY.
 *
 * Stores temporary OTP-related data with TTL-based expiry.
 * Uses chrome.storage.local when available, falls back to sessionStorage.
 * Never stores raw credentials or real OTP tokens persistently.
 */
(function initVisaFlowXOtpSecureStorage(global) {
  "use strict";

  const OTP_STORAGE_PREFIX = "vfx.otp.";
  const DEFAULT_TTL_MS     = 5 * 60 * 1000; // 5 minutes

  function log(msg) {
    console.log("[VisaFlowX][OtpSecureStorage]", msg);
  }

  function hasChromeStorage() {
    return Boolean(typeof chrome !== "undefined" && chrome?.storage?.local);
  }

  function hasSessionStorage() {
    try { sessionStorage.setItem("__vfx_test", "1"); sessionStorage.removeItem("__vfx_test"); return true; }
    catch (_) { return false; }
  }

  // ── Write ─────────────────────────────────────────────────────
  async function set(key, value, ttlMs = DEFAULT_TTL_MS) {
    const storageKey = OTP_STORAGE_PREFIX + key;
    const entry = { value, expiresAt: Date.now() + ttlMs, savedAt: Date.now() };

    if (hasChromeStorage()) {
      await chrome.storage.local.set({ [storageKey]: entry });
    } else if (hasSessionStorage()) {
      sessionStorage.setItem(storageKey, JSON.stringify(entry));
    }
    log(`Set: ${key} (TTL: ${Math.round(ttlMs / 1000)}s)`);
  }

  // ── Read ─────────────────────────────────────────────────────
  async function get(key) {
    const storageKey = OTP_STORAGE_PREFIX + key;
    let entry = null;

    if (hasChromeStorage()) {
      const result = await chrome.storage.local.get(storageKey).catch(() => ({}));
      entry = result[storageKey] || null;
    } else if (hasSessionStorage()) {
      try { entry = JSON.parse(sessionStorage.getItem(storageKey) || "null"); } catch (_) {}
    }

    if (!entry) return null;
    if (Date.now() > Number(entry.expiresAt || 0)) {
      await remove(key);
      log(`Expired: ${key}`);
      return null;
    }
    return entry.value;
  }

  // ── Remove ────────────────────────────────────────────────────
  async function remove(key) {
    const storageKey = OTP_STORAGE_PREFIX + key;
    if (hasChromeStorage()) {
      await chrome.storage.local.remove(storageKey).catch(() => {});
    } else if (hasSessionStorage()) {
      sessionStorage.removeItem(storageKey);
    }
  }

  // ── Clear all OTP entries ────────────────────────────────────
  async function clearAll() {
    if (hasChromeStorage()) {
      const all = await chrome.storage.local.get(null).catch(() => ({}));
      const otpKeys = Object.keys(all).filter((k) => k.startsWith(OTP_STORAGE_PREFIX));
      if (otpKeys.length) await chrome.storage.local.remove(otpKeys);
    } else if (hasSessionStorage()) {
      Object.keys(sessionStorage)
        .filter((k) => k.startsWith(OTP_STORAGE_PREFIX))
        .forEach((k) => sessionStorage.removeItem(k));
    }
    log("All OTP storage cleared");
  }

  const OtpSecureStorage = Object.freeze({ set, get, remove, clearAll });

  global.VisaFlowX = Object.assign(global.VisaFlowX || {}, { OtpSecureStorage });

  if (typeof module !== "undefined" && module.exports) {
    module.exports = OtpSecureStorage;
  }
})(typeof globalThis !== "undefined" ? globalThis : this);
