import 'package:flutter_test/flutter_test.dart';
import 'package:openim/company/rtc/call_session_guard.dart';
import 'package:openim/company/rtc/livekit_call_config.dart';

void main() {
  test('配置门：内网地址与换票路径齐全时才打开入口', () {
    expect(LiveKitCallConfig.rtcTokenPath, '/api/rtc_token');
    expect(LiveKitCallConfig.endpointsReady, isTrue);
    expect(LiveKitCallConfig.enabled, LiveKitCallConfig.shipped);
  });

  test('占线时拒绝第二路呼出/呼入', () {
    final guard = CallSessionGuard();
    expect(guard.startOutgoing('room-a'), isNull);
    expect(guard.startOutgoing('room-b'), 'busy');
    expect(guard.startIncoming('room-c'), 'busy');
    guard.dispose();
    expect(guard.isBusy, isFalse);
    expect(guard.startIncoming('room-d'), isNull);
    guard.dispose();
  });

  test('同一房间同一信令只处理一次', () {
    final guard = CallSessionGuard();
    expect(guard.acceptSignaling(customType: 200, roomID: 'r1'), isTrue);
    expect(guard.acceptSignaling(customType: 200, roomID: 'r1'), isFalse);
    expect(guard.acceptSignaling(customType: 201, roomID: 'r1'), isTrue);
    expect(guard.acceptSignaling(customType: 200, roomID: ''), isFalse);
    guard.dispose();
  });

  test('接听后取消超时，销毁后释放计时器', () async {
    var timedOut = false;
    final guard = CallSessionGuard(inviteTimeout: const Duration(milliseconds: 40));
    guard.onTimeout = () => timedOut = true;
    guard.startOutgoing('room-t');
    guard.markConnected();
    await Future<void>.delayed(const Duration(milliseconds: 80));
    expect(timedOut, isFalse);
    expect(guard.phase, VoiceCallPhase.inCall);

    guard.dispose();
    expect(guard.phase, VoiceCallPhase.idle);
    expect(guard.roomID, isNull);
  });

  test('呼出超时回调', () async {
    var timedOut = false;
    final guard = CallSessionGuard(inviteTimeout: const Duration(milliseconds: 30));
    guard.onTimeout = () => timedOut = true;
    guard.startOutgoing('room-t');
    await Future<void>.delayed(const Duration(milliseconds: 80));
    expect(timedOut, isTrue);
    guard.dispose();
  });

  test('sameRoom 只认当前房间', () {
    final guard = CallSessionGuard();
    guard.startIncoming('room-1');
    expect(guard.sameRoom('room-1'), isTrue);
    expect(guard.sameRoom('room-2'), isFalse);
    expect(guard.sameRoom(null), isFalse);
    guard.dispose();
  });
}
