// storage.native.js — implementazione Capacitor (Preferences + CryptoJS)

import { Storage } from "./storage.js";
const { Preferences } = Capacitor.Plugins;

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

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

  await Preferences.set({
    key: "launcherConfig",
    value: encrypted
  });
};

Storage.loadConfig = async () => {
  const { value } = await Preferences.get({ key: "launcherConfig" });
  if (!value) return null;

  try {
    const bytes = CryptoJS.AES.decrypt(value, 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();

  await Preferences.set({
    key: "jsonApps",
    value: encrypted
  });
};

Storage.loadApps = async () => {
  const { value } = await Preferences.get({ key: "jsonApps" });
  if (!value) return null;

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

// ---------------- ORDER ----------------
Storage.saveAppsOrder = async (order) => {
  await Preferences.set({
    key: "appsOrder",
    value: JSON.stringify(order)
  });
};

Storage.loadAppsOrder = async () => {
  const { value } = await Preferences.get({ key: "appsOrder" });
  if (!value) return null;

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

export default Storage;
