import 'package:shared_preferences/shared_preferences.dart';

abstract interface class SessionService {
  Future<String?> getLastRoom();
  Future<void> setLastRoom(String? room);
  Future<void> clearLastRoom();
}

final class SharedPreferencesSessionService implements SessionService {
  SharedPreferencesSessionService({SharedPreferences? prefs}) : _prefs = prefs;

  SharedPreferences? _prefs;

  Future<SharedPreferences> get _preferences async {
    if (_prefs != null) return _prefs!;
    _prefs = await SharedPreferences.getInstance();
    return _prefs!;
  }

  @override
  Future<String?> getLastRoom() async {
    final prefs = await _preferences;
    return prefs.getString(_roomKey);
  }

  @override
  Future<void> setLastRoom(String? room) async {
    final prefs = await _preferences;
    if (room == null) {
      await prefs.remove(_roomKey);
    } else {
      await prefs.setString(_roomKey, room);
    }
  }

  @override
  Future<void> clearLastRoom() async {
    final prefs = await _preferences;
    await prefs.remove(_roomKey);
  }

  static const _roomKey = 'asr_last_room';
}
