// Typed wrapper around the native AudioRoute Capacitor plugin.
//
// The plugin (AudioRoutePlugin.java) flips the in-call audio OUTPUT between the
// loudspeaker and the earpiece during a DM voice call. This is the ONLY way to
// offer a «громкая связь» toggle: call audio is owned by the WebView's WebRTC
// stack, which routes to the earpiece by default with no in-WebView lever
// (setSinkId / selectAudioOutput are unimplemented on Android WebView).
//
// Android-only. On web / iOS the OS handles output routing, so every method is
// a no-op and `available()` returns false (the UI hides the toggle there).

import { registerPlugin } from '@capacitor/core';
import { isAndroidPlatform } from '../../utils/capacitor';

interface AudioRoutePlugin {
  setSpeaker(options: { on: boolean }): Promise<{ speaker: boolean }>;
  getRoute(): Promise<{ speaker: boolean }>;
  clear(): Promise<void>;
}

const plugin = registerPlugin<AudioRoutePlugin>('AudioRoute');

export const callAudioRoute = {
  // Whether an in-app speaker/earpiece toggle can do anything on this platform.
  available(): boolean {
    return isAndroidPlatform();
  },

  // Flip the call output to speaker (on) or earpiece (off). Resolves with the
  // route the native side OBSERVES afterwards — some OEM WebViews resist
  // app-side routing, so JS trusts the resolved value, not the request.
  async setSpeaker(on: boolean): Promise<boolean> {
    if (!isAndroidPlatform()) return on;
    try {
      const res = await plugin.setSpeaker({ on });
      return res.speaker;
    } catch {
      // Plugin missing / threw — report the requested state so the UI doesn't
      // get stuck, but the actual route is whatever WebRTC chose.
      return on;
    }
  },

  // Read the currently active output route (true = loudspeaker).
  async getRoute(): Promise<boolean> {
    if (!isAndroidPlatform()) return false;
    try {
      const res = await plugin.getRoute();
      return res.speaker;
    } catch {
      return false;
    }
  },

  // Restore the platform-default route. MUST be called on every call teardown
  // (hangup / remote hangup / error) or the next call inherits a forced route.
  clear(): Promise<void> {
    if (!isAndroidPlatform()) return Promise.resolve();
    return plugin.clear().catch(() => undefined);
  },
};
