import 'dart:convert';
import 'dart:developer';

import 'package:injectable/injectable.dart';
import 'package:shared_preferences/shared_preferences.dart';

import '../../../common/constant/local_storage_key.dart';
import '../../../domain/user/user.dart';
import '../../user/user_dtos.dart';

@injectable
class AuthLocalDataProvider {
  final SharedPreferences _sharedPreferences;
  final String _logName = 'AuthLocalDataProvider';

  AuthLocalDataProvider(this._sharedPreferences);

  Future<void> saveToken(String token) async {
    await _sharedPreferences.setString(LocalStorageKey.token, token);
  }

  Future<String?> getToken() async {
    return _sharedPreferences.getString(LocalStorageKey.token);
  }

  Future<void> deleteToken() async {
    await _sharedPreferences.remove(LocalStorageKey.token);
  }

  Future<bool> hasToken() async {
    return _sharedPreferences.containsKey(LocalStorageKey.token);
  }

  Future<void> saveCurrentUser(UserDto user) async {
    final userJsonString = jsonEncode(user.toJson());
    await _sharedPreferences.setString(LocalStorageKey.user, userJsonString);
  }

  Future<User> currentUser() async {
    final userString = _sharedPreferences.getString(LocalStorageKey.user);
    if (userString == null) return User.empty();

    final Map<String, dynamic> userMap = jsonDecode(userString);
    final userDto = UserDto.fromJson(userMap);
    return userDto.toDomain();
  }

  Future<void> deleteCurrentUser() async {
    await _sharedPreferences.remove(LocalStorageKey.user);
  }

  Future<void> deleteAllAuth() async {
    try {
      await _sharedPreferences.remove(LocalStorageKey.token);
      await _sharedPreferences.remove(LocalStorageKey.user);
    } catch (e) {
      log('deleteAllAuthError', name: _logName, error: e);
    }
  }
}
