import '../../../../core/errors/errors.dart';
import '../../../../core/errors/result.dart';
import '../../domain/entities/server_config.dart';
import '../../domain/repositories/settings_repository.dart';
import '../datasources/settings_local_datasource.dart';
import '../datasources/settings_remote_datasource.dart';

class SettingsRepositoryImpl implements SettingsRepository {
  final SettingsLocalDataSource _local;
  final SettingsRemoteDataSource _remote;

  SettingsRepositoryImpl(this._local, this._remote);

  @override
  Future<String?> getApiUrl() => _local.getApiUrl();

  @override
  Future<Result<void>> saveApiUrl(String url) async {
    try {
      await _local.saveApiUrl(url);
      return const Result.success(null);
    } catch (e) {
      return const Result.failure(AppError.unknown(message: 'Failed to save API URL'));
    }
  }

  @override
  Future<String?> getLanguageCode() => _local.getLanguageCode();

  @override
  Future<Result<void>> saveLanguageCode(String code) async {
    try {
      await _local.saveLanguageCode(code);
      return const Result.success(null);
    } catch (e) {
      return const Result.failure(AppError.unknown(message: 'Failed to save language'));
    }
  }

  @override
  Future<Result<ServerConfig>> getServerConfig() async {
    final local = await _local.getServerConfig();
    if (local != null) {
      return Result.success(local);
    }
    return refreshServerConfig();
  }

  @override
  Future<Result<ServerConfig>> refreshServerConfig() async {
    final result = await _remote.getServerConfig();
    result.when(
      onSuccess: (config) async => await _local.saveServerConfig(config),
      onFailure: (_) {},
    );
    return result;
  }

  @override
  Future<Result<bool>> getNotificationsEnabled() async {
    return const Result.success(true);
  }

  @override
  Future<Result<void>> setNotificationsEnabled(bool enabled) async {
    return const Result.success(null);
  }

  @override
  Future<Result<bool>> getDarkModeEnabled() async {
    return const Result.success(false);
  }

  @override
  Future<Result<void>> setDarkModeEnabled(bool enabled) async {
    return const Result.success(null);
  }

  @override
  Future<Result<void>> clearAllData() async {
    return const Result.success(null);
  }
}
