import 'package:dio/dio.dart';
import '../../../../core/config/api_endpoints.dart';
import '../models/voice_session_model.dart';

/// Remote datasource for voice session API operations.
class VoiceDatasource {
  final Dio _dio;

  VoiceDatasource(this._dio);

  /// Creates a new voice session on the backend.
  Future<VoiceSessionModel> createSession() async {
    final response = await _dio.post('${ApiEndpoints.voice}/sessions');
    return VoiceSessionModel.fromJson(response.data as Map<String, dynamic>);
  }

  /// Ends (deletes) a voice session on the backend.
  Future<void> deleteSession(String sessionId) async {
    await _dio.delete('${ApiEndpoints.voice}/sessions/$sessionId');
  }

  /// Fetches the currently active voice session, if any.
  Future<VoiceSessionModel?> getActiveSession() async {
    try {
      final response = await _dio.get('${ApiEndpoints.voice}/sessions/active');
      if (response.data != null) {
        return VoiceSessionModel.fromJson(response.data as Map<String, dynamic>);
      }
      return null;
    } on DioException catch (e) {
      if (e.response?.statusCode == 404) return null;
      rethrow;
    }
  }
}
