import {
  describe,
  it,
  expect,
  beforeEach,
  vi
} from 'vitest';
import { ProvisionSecretStoreService } from './provision-secret-store.service';
import { ElectronBridgeService } from '../../../../core/platform/electron/electron-bridge.service';

describe('ProvisionSecretStoreService', () => {
  let service: ProvisionSecretStoreService;
  let electronBridge: ElectronBridgeService;

  beforeEach(() => {
    const sessionStorageMap = new Map<string, string>();

    vi.stubGlobal('sessionStorage', {
      getItem: (key: string) => sessionStorageMap.get(key) ?? null,
      setItem: (key: string, value: string) => { sessionStorageMap.set(key, value); },
      removeItem: (key: string) => { sessionStorageMap.delete(key); },
      clear: () => { sessionStorageMap.clear(); }
    });

    electronBridge = {
      isAvailable: false,
      getApi: () => null,
      requireApi: () => {
        throw new Error('Electron API is not available in this runtime.');
      }
    } as ElectronBridgeService;

    service = new ProvisionSecretStoreService(electronBridge);
  });

  it('stores and retrieves provision secrets in session storage when electron is unavailable', async () => {
    await service.storeSecret('home-user-1', 'secret-abc');
    await expect(service.getSecret('home-user-1')).resolves.toBe('secret-abc');
  });

  it('uses electron secure storage when available', async () => {
    const storeProvisionSecret = vi.fn(async () => true);
    const getProvisionSecret = vi.fn(async () => 'electron-secret');

    electronBridge = {
      isAvailable: true,
      getApi: () => ({
        storeProvisionSecret,
        getProvisionSecret
      }),
      requireApi: () => ({
        storeProvisionSecret,
        getProvisionSecret
      })
    } as unknown as ElectronBridgeService;

    service = new ProvisionSecretStoreService(electronBridge);

    await service.storeSecret('home-user-1', 'secret-abc');
    await expect(service.getSecret('home-user-1')).resolves.toBe('electron-secret');

    expect(storeProvisionSecret).toHaveBeenCalledWith('home-user-1', 'secret-abc');
    expect(getProvisionSecret).toHaveBeenCalledWith('home-user-1');
  });
});
