// storage.web.js — implementazione Web (localStorage + CryptoJS)

import { Storage } from "./storage.js";

const SECRET_KEY = "chiave-super-segreta-123";

// ---------------- CONFIG ----------------
Storage.saveConfig = async (data) => {
  const encrypted = CryptoJS.AES.encrypt(
    JSON.stringify(data),
    SECRET_KEY
  ).toString();

  localStorage.setItem("launcherConfig", encrypted);
};

Storage.loadConfig = async () => {
  const encrypted = localStorage.getItem("launcherConfig");
  if (!encrypted) return null;

  try {
    const bytes = CryptoJS.AES.decrypt(encrypted, SECRET_KEY);
    return JSON.parse(bytes.toString(CryptoJS.enc.Utf8));
  } catch {
    return null;
  }
};

// ---------------- APPS ----------------
Storage.saveApps = async (apps) => {
  const encrypted = CryptoJS.AES.encrypt(
    JSON.stringify(apps),
    SECRET_KEY
  ).toString();

  localStorage.setItem("jsonApps", encrypted);
};

Storage.loadApps = async () => {
  const encrypted = localStorage.getItem("jsonApps");
  if (!encrypted) return null;

  try {
    const bytes = CryptoJS.AES.decrypt(encrypted, SECRET_KEY);
    return JSON.parse(bytes.toString(CryptoJS.enc.Utf8));
  } catch {
    return null;
  }
};

// ---------------- ORDER ----------------
Storage.saveAppsOrder = async (order) => {
  localStorage.setItem("appsOrder", JSON.stringify(order));
};

Storage.loadAppsOrder = async () => {
  const raw = localStorage.getItem("appsOrder");
  if (!raw) return null;

  try {
    return JSON.parse(raw);
  } catch {
    return null;
  }
};

export default Storage;
