/**
 * Storage adapter for browser extensions that routes ALL storage calls through
 * the background service worker via runtime messaging. No direct access to
 * page-level storage APIs from content/page contexts.
 */
class StorageAdapter {
  constructor() {
    this.runtime = (typeof globalThis.chrome?.runtime !== 'undefined' && globalThis.chrome.runtime)
      ? globalThis.chrome.runtime
      : (globalThis.browser?.runtime || null);
    if (!this.runtime || !this.runtime.sendMessage) {
      throw new Error('LlamaStorageAdapter: Extension runtime messaging unavailable.');
    }
  }

  async get(keys) {
    // Support string key only for simplicity; wrap complex requests at call site
    const key = Array.isArray(keys) ? keys[0] : (typeof keys === 'string' ? keys : Object.keys(keys || {})[0]);
    const defaultValue = (typeof keys === 'object' && !Array.isArray(keys)) ? keys[key] : null;
    return new Promise((resolve, reject) => {
      this.runtime.sendMessage({
        type: 'LLAMMA_SHADES_STORAGE_GET',
        key,
        defaultValue
      }, (response) => {
        const lastErr = globalThis.chrome?.runtime?.lastError;
        if (lastErr) return reject(new Error(lastErr.message));
        if (!response || response.error) return reject(new Error(response?.error || 'No response'));
        // Return the raw stored value directly, not wrapped as { [key]: value }
        resolve(response);
      });
    });
  }

  async set(items) {
    const key = Object.keys(items || {})[0];
    const value = items ? items[key] : undefined;
    return new Promise((resolve, reject) => {
      this.runtime.sendMessage({
        type: 'LLAMMA_SHADES_STORAGE_SET',
        key,
        value
      }, (response) => {
        const lastErr = globalThis.chrome?.runtime?.lastError;
        if (lastErr) return reject(new Error(lastErr.message));
        if (!response || response.error) return reject(new Error(response?.error || 'No response'));
        resolve();
      });
    });
  }

  async remove(keys) {
    const key = Array.isArray(keys) ? keys[0] : keys;
    return new Promise((resolve, reject) => {
      this.runtime.sendMessage({
        type: 'LLAMMA_SHADES_STORAGE_REMOVE',
        key
      }, (response) => {
        const lastErr = globalThis.chrome?.runtime?.lastError;
        if (lastErr) return reject(new Error(lastErr.message));
        if (response && response.error) return reject(new Error(response.error));
        resolve();
      });
    });
  }
}

window.LlamaStorageAdapter = StorageAdapter;
