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

const SESSION_STORAGE_PREFIX = 'metoyou.provisionSecret.';

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

  constructor(electronBridge: ElectronBridgeService = inject(ElectronBridgeService)) {
    this.electronBridge = electronBridge;
  }

  async storeSecret(homeUserId: string, secret: string): Promise<void> {
    const api = this.electronBridge.getApi();

    if (api?.storeProvisionSecret) {
      await api.storeProvisionSecret(homeUserId, secret);
      return;
    }

    sessionStorage.setItem(this.sessionKey(homeUserId), secret);
  }

  async getSecret(homeUserId: string): Promise<string | null> {
    const api = this.electronBridge.getApi();

    if (api?.getProvisionSecret) {
      return api.getProvisionSecret(homeUserId);
    }

    return sessionStorage.getItem(this.sessionKey(homeUserId));
  }

  async hasSecret(homeUserId: string): Promise<boolean> {
    const secret = await this.getSecret(homeUserId);

    return !!secret;
  }

  private sessionKey(homeUserId: string): string {
    return `${SESSION_STORAGE_PREFIX}${homeUserId}`;
  }
}

export function generateProvisionSecret(): string {
  const bytes = new Uint8Array(32);

  crypto.getRandomValues(bytes);

  return Array.from(bytes, (byte) => byte.toString(16).padStart(2, '0')).join('');
}
