import { Injectable, inject } from '@angular/core';
import { getUserScopedStorageKey } from '../../../../core/storage/current-user-storage';
import { ElectronBridgeService } from '../../../../core/platform/electron/electron-bridge.service';

@Injectable({ providedIn: 'root' })
export class PluginDesktopStateService {
  private readonly electronBridge = inject(ElectronBridgeService);

  async readJson<TValue>(key: string, fallback: TValue): Promise<TValue> {
    const raw = await this.readRaw(key);

    if (!raw) {
      return fallback;
    }

    try {
      return JSON.parse(raw) as TValue;
    } catch {
      return fallback;
    }
  }

  async writeJson(key: string, value: unknown): Promise<void> {
    await this.writeRaw(key, JSON.stringify(value));
  }

  private async readRaw(key: string): Promise<string | null> {
    const scopedKey = getUserScopedStorageKey(key);
    const api = this.electronBridge.getApi();

    if (api) {
      return await api.query<string | null>({
        type: 'get-meta',
        payload: { key: scopedKey }
      });
    }

    return localStorage.getItem(scopedKey);
  }

  private async writeRaw(key: string, value: string): Promise<void> {
    const scopedKey = getUserScopedStorageKey(key);
    const api = this.electronBridge.getApi();

    if (api) {
      await api.command({
        type: 'save-meta',
        payload: { key: scopedKey, value }
      });

      return;
    }

    localStorage.setItem(scopedKey, value);
  }
}
