import '../../../../core/config/app_config.dart';
import '../../domain/entities/voice_session.dart';
import '../../domain/repositories/voice_repository.dart';
import '../datasources/voice_datasource.dart';

class VoiceRepositoryImpl implements VoiceRepository {
  final VoiceDatasource _datasource;
  final AppConfig _config;

  VoiceRepositoryImpl({
    required VoiceDatasource datasource,
    required AppConfig config,
  })  : _datasource = datasource,
        _config = config;

  @override
  Future<VoiceSession> startSession() async {
    final model = await _datasource.createSession();
    final session = model.toEntity();

    // If the backend didn't provide a WebSocket URL, construct one
    if (session.websocketUrl == null) {
      return session.copyWith(
        websocketUrl: '${_config.wsBaseUrl}/api/v1/voice/ws/${session.id}',
      );
    }

    // If the backend returned a relative path, prepend the wsBaseUrl host
    if (session.websocketUrl!.startsWith('/')) {
      final uri = Uri.parse(_config.wsBaseUrl);
      return session.copyWith(
        websocketUrl:
            '${uri.scheme}://${uri.host}:${uri.port}${session.websocketUrl}',
      );
    }

    return session;
  }

  @override
  Future<void> endSession(String sessionId) async {
    await _datasource.deleteSession(sessionId);
  }

  @override
  Future<VoiceSession?> getActiveSession() async {
    final model = await _datasource.getActiveSession();
    return model?.toEntity();
  }
}
