import { DEFAULT_SETTINGS, SETTINGS_KEY } from "../../shared/settings.js";
import { parseSettings } from "../../shared/schema.js";

export async function getStoredSettings() {
  const stored = await chrome.storage.local.get([SETTINGS_KEY, ...Object.keys(DEFAULT_SETTINGS)]);
  const merged = {
    ...DEFAULT_SETTINGS,
    ...(stored[SETTINGS_KEY] || {})
  };

  for (const key of Object.keys(DEFAULT_SETTINGS)) {
    if (typeof stored[key] !== "undefined" && merged[key] === DEFAULT_SETTINGS[key]) {
      merged[key] = stored[key];
    }
  }

  return parseSettings(merged);
}

export async function saveStoredSettings(input) {
  const settings = parseSettings(input || {});
  await chrome.storage.local.set({
    [SETTINGS_KEY]: settings,
    ...settings
  });
}
