//
//  HumandAudioSessionPolicy.swift
//  humand
//

import AVFoundation
import StreamVideo

/// Custom audio session policy applied during call cleanup.
/// Keeps the audio session active with playback configuration so that
/// media playback and audio routing remain stable after a call ends.
struct HumandAudioSessionPolicy: AudioSessionPolicy {
  func configuration(
    for callSettings: CallSettings,
    ownCapabilities: Set<OwnCapability>
  ) -> AudioSessionConfiguration {
    return .init(
      isActive: true,
      category: .playback,
      mode: .default,
      options: .allowBluetoothA2DP,
      overrideOutputAudioPort: nil
    )
  }
}

/// Audio session policy for livestream viewers.
/// Uses .playAndRecord (matching WebRTC's internal requirement) with .default
/// mode and .defaultToSpeaker so audio always routes through the speaker
/// instead of the earpiece. The SDK reducer only applies overrideOutputAudioPort
/// when the state category is .playAndRecord; using .playback would cause a
/// mismatch with WebRTC's actual category and skip the speaker override.
struct HumandLivestreamViewerPolicy: AudioSessionPolicy {
  func configuration(
    for callSettings: CallSettings,
    ownCapabilities: Set<OwnCapability>
  ) -> AudioSessionConfiguration {
    return .init(
      isActive: callSettings.audioOutputOn,
      category: .playAndRecord,
      mode: .default,
      options: [.allowBluetoothA2DP, .defaultToSpeaker],
      overrideOutputAudioPort: callSettings.speakerOn ? .speaker : .none
    )
  }
}
