import { loadAuthenticationSession, revokeAuthenticatedDevice } from "../auth/auth-api.js";

const STORAGE_PREFIXES = ["codexRemote.", "code-remote-manager."];
const CACHE_PREFIX = "code-remote-manager-";

export async function resetThisDeviceData({
  loadSession = loadAuthenticationSession,
  revokeDevice = revokeAuthenticatedDevice,
  localStorage = globalThis.localStorage,
  sessionStorage = globalThis.sessionStorage,
  cacheStorage = globalThis.caches
} = {}) {
  try {
    const session = await loadSession();
    const deviceId = cleanDeviceId(session?.device?.id);
    if (!deviceId) throw new Error("device_not_found");
    if (deviceId !== "authentication-exempt") await revokeDevice(deviceId);
  } catch {
    throw new Error("device_reset_failed");
  }

  try {
    await clearThisDeviceData({ localStorage, sessionStorage, cacheStorage });
  } catch {
    throw new Error("device_reset_incomplete");
  }
}

export async function clearThisDeviceData({
  localStorage = globalThis.localStorage,
  sessionStorage = globalThis.sessionStorage,
  cacheStorage = globalThis.caches
} = {}) {
  const failures = [];
  for (const storage of [localStorage, sessionStorage]) {
    try { clearAppStorage(storage); } catch { failures.push("storage"); }
  }
  try { await clearAppCaches(cacheStorage); } catch { failures.push("cache"); }
  if (failures.length > 0) throw new Error("device_reset_incomplete");
}

function clearAppStorage(storage) {
  if (!storage) return;
  const keys = [];
  for (let index = 0; index < storage.length; index += 1) {
    const key = storage.key(index);
    if (typeof key === "string" && STORAGE_PREFIXES.some((prefix) => key.startsWith(prefix))) keys.push(key);
  }
  for (const key of keys) storage.removeItem(key);
}

async function clearAppCaches(cacheStorage) {
  if (!cacheStorage?.keys || !cacheStorage?.delete) return;
  const keys = await cacheStorage.keys();
  await Promise.all(keys.filter((key) => key.startsWith(CACHE_PREFIX)).map((key) => cacheStorage.delete(key)));
}

function cleanDeviceId(value) {
  return typeof value === "string" && value.trim() ? value.trim() : "";
}
