import { Injectable, inject } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { firstValueFrom } from 'rxjs';
import { environment } from '../../environments/environment';

/**
 * BMS web-push opt-in. Fetches the VAPID key, registers the service worker,
 * subscribes the browser, and posts the subscription to the backend. Silently
 * no-ops when push is unconfigured or unsupported.
 */
@Injectable({ providedIn: 'root' })
export class PushService {
  private http = inject(HttpClient);
  private base = environment.apiBase;

  async enable(): Promise<boolean> {
    try {
      if (!('serviceWorker' in navigator) || !('PushManager' in window)) { return false; }

      const key = await firstValueFrom(
        this.http.get<{ data: { enabled: boolean; public_key: string | null } }>(`${this.base}/push/key`)
      );
      if (!key?.data?.enabled || !key.data.public_key) { return false; }

      const perm = await Notification.requestPermission();
      if (perm !== 'granted') { return false; }

      const reg = await navigator.serviceWorker.register('push-sw.js');
      const sub = await reg.pushManager.subscribe({
        userVisibleOnly: true,
        applicationServerKey: this.urlBase64ToUint8Array(key.data.public_key),
      });

      await firstValueFrom(this.http.post(`${this.base}/employee/push/subscribe`, { subscription: sub.toJSON() }));
      return true;
    } catch {
      return false;
    }
  }

  private urlBase64ToUint8Array(base64: string): Uint8Array {
    const padding = '='.repeat((4 - (base64.length % 4)) % 4);
    const b64 = (base64 + padding).replace(/-/g, '+').replace(/_/g, '/');
    const raw = atob(b64);
    const out = new Uint8Array(raw.length);
    for (let i = 0; i < raw.length; i++) { out[i] = raw.charCodeAt(i); }
    return out;
  }
}
