import 'dart:convert';
import 'package:shared_preferences/shared_preferences.dart';
import '../../../../core/constants/storage_keys.dart';
import '../../domain/entities/server_config.dart';

abstract class SettingsLocalDataSource {
  Future<String?> getApiUrl();
  Future<void> saveApiUrl(String url);
  Future<String?> getLanguageCode();
  Future<void> saveLanguageCode(String code);
  Future<ServerConfig?> getServerConfig();
  Future<void> saveServerConfig(ServerConfig config);
}

class SettingsLocalDataSourceImpl implements SettingsLocalDataSource {
  final SharedPreferences _prefs;

  SettingsLocalDataSourceImpl(this._prefs);

  @override
  Future<String?> getApiUrl() async {
    return _prefs.getString(StorageKeys.apiUrl);
  }

  @override
  Future<void> saveApiUrl(String url) async {
    await _prefs.setString(StorageKeys.apiUrl, url);
  }

  @override
  Future<String?> getLanguageCode() async {
    return _prefs.getString(StorageKeys.languageCode);
  }

  @override
  Future<void> saveLanguageCode(String code) async {
    await _prefs.setString(StorageKeys.languageCode, code);
  }

  @override
  Future<ServerConfig?> getServerConfig() async {
    final jsonString = _prefs.getString(StorageKeys.serverConfig);
    if (jsonString == null) return null;
    try {
      final json = jsonDecode(jsonString) as Map<String, dynamic>;
      return ServerConfig.fromJson(json);
    } catch (_) {
      return null;
    }
  }

  @override
  Future<void> saveServerConfig(ServerConfig config) async {
    final jsonString = jsonEncode(config.toJson());
    await _prefs.setString(StorageKeys.serverConfig, jsonString);
  }
}
