import { Injectable, inject } from '@angular/core';
import { ElectronBridgeService } from '../../../../core/platform/electron/electron-bridge.service';
import type { WindowStateSnapshot } from '../../../../core/platform/electron/electron-api.models';
import { PlatformService } from '../../../../core/platform';
import type { NotificationDisplayPayload } from '../../domain/models/notification.model';

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

  async showNotification(payload: NotificationDisplayPayload): Promise<void> {
    const api = this.electronBridge.getApi();

    if (api?.showDesktopNotification) {
      await api.showDesktopNotification(payload);
      return;
    }

    if (!this.platform.isBrowser || typeof Notification === 'undefined') {
      return;
    }

    let permission = Notification.permission;

    if (permission === 'default') {
      permission = await Notification.requestPermission();
    }

    if (permission !== 'granted') {
      return;
    }

    const notification = new Notification(payload.title, { body: payload.body });

    notification.onclick = () => window.focus();
  }

  async requestAttention(): Promise<void> {
    const api = this.electronBridge.getApi();

    if (api?.requestWindowAttention) {
      await api.requestWindowAttention();
    }
  }

  async clearAttention(): Promise<void> {
    const api = this.electronBridge.getApi();

    if (api?.clearWindowAttention) {
      await api.clearWindowAttention();
    }
  }

  onWindowStateChanged(listener: (state: WindowStateSnapshot) => void): (() => void) | null {
    const api = this.electronBridge.getApi();

    if (!api?.onWindowStateChanged) {
      return null;
    }

    return api.onWindowStateChanged(listener);
  }
}
