import type { CallNotificationActionIntent, CallNotificationPayload } from '../../logic/call-notification.rules';
import type { MobileNotificationAdapter } from '../../contracts/mobile.contracts';

type CallActionHandler = (input: { callId: string; intent: CallNotificationActionIntent }) => void;

/** Browser Notification API fallback for web and Capacitor dev shells. */
export class WebMobileNotificationsAdapter implements MobileNotificationAdapter {
  private actionHandler: CallActionHandler | null = null;

  async initialize(): Promise<void> {
    return;
  }

  async requestPermission(): Promise<boolean> {
    if (typeof Notification === 'undefined') {
      return false;
    }

    if (Notification.permission === 'granted') {
      return true;
    }

    if (Notification.permission === 'denied') {
      return false;
    }

    const permission = await Notification.requestPermission();

    return permission === 'granted';
  }

  async showCallNotification(payload: CallNotificationPayload): Promise<void> {
    const granted = await this.requestPermission();

    if (!granted) {
      return;
    }

    const notification = new Notification(payload.title, {
      body: payload.body,
      tag: `toju-call-${payload.callId}-${payload.kind}`
    });

    notification.onclick = () => {
      window.focus();
      this.actionHandler?.({
        callId: payload.callId,
        intent: payload.kind === 'incoming' ? 'answer' : 'toggle-mute'
      });
    };
  }

  async dismissCallNotification(_callId: string, _kind: CallNotificationPayload['kind']): Promise<void> {
    return;
  }

  onActionSelected(handler: CallActionHandler): void {
    this.actionHandler = handler;
  }
}
