import type { StorageLike, StoredKeys } from "./types";

export const DEFAULT_KEYS_STORAGE_KEY = "geo_api_keys_v1";

export function saveKeys(storage: StorageLike, keys: StoredKeys, storageKey = DEFAULT_KEYS_STORAGE_KEY): void {
  storage.setItem(storageKey, JSON.stringify(keys));
}

export function loadKeys(storage: StorageLike, storageKey = DEFAULT_KEYS_STORAGE_KEY): StoredKeys | null {
  const raw = storage.getItem(storageKey);
  if (!raw) {
    return null;
  }
  const parsed = JSON.parse(raw) as StoredKeys;
  if (!parsed.publicKey || !parsed.privateKey) {
    return null;
  }
  return parsed;
}

export function clearKeys(storage: StorageLike, storageKey = DEFAULT_KEYS_STORAGE_KEY): void {
  storage.removeItem(storageKey);
}
