import 'package:agora_rtc_engine/agora_rtc_engine.dart';
import 'package:flutter/foundation.dart';

import '../constants/app_constants.dart';
import '../network/api_client.dart';

class CallService {
  final ApiClient _apiClient;
  RtcEngine? _engine;

  CallService(this._apiClient);

  Future<Map<String, dynamic>?> requestToken(String channelName) async {
    final res = await _apiClient.dio.post('/shared/call/token', data: {'channelName': channelName});
    final data = res.data['data'];
    return data is Map<String, dynamic> ? data : null;
  }

  Future<void> notifyIncomingCall({required int receiverId, required String channelName}) async {
    await _apiClient.dio.post('/shared/call/notify', data: {
      'receiverId': receiverId,
      'channelName': channelName,
    });
  }

  Future<bool> joinChannel({required String channelName, int uid = 0}) async {
    try {
      final tokenData = await requestToken(channelName);
      final token = tokenData?['token']?.toString();
      _engine ??= createAgoraRtcEngine();
      await _engine!.initialize(const RtcEngineContext(appId: AppConstants.agoraAppId));
      await _engine!.enableAudio();
      await _engine!.joinChannel(
        token: token ?? '',
        channelId: channelName,
        uid: uid,
        options: const ChannelMediaOptions(),
      );
      return true;
    } catch (e) {
      debugPrint('Agora join skipped: $e');
      return false;
    }
  }

  Future<void> leave() async {
    await _engine?.leaveChannel();
  }

  Future<void> dispose() async {
    await _engine?.release();
    _engine = null;
  }
}
