import 'package:flutter/foundation.dart';
import 'package:flutter_secure_storage/flutter_secure_storage.dart';
import 'package:shared_preferences/shared_preferences.dart';

class SecureStorage {
  static const _storage = FlutterSecureStorage(
    aOptions: AndroidOptions(encryptedSharedPreferences: true),
  );

  static const _keyAccess = 'access_token';
  static const _keyRefresh = 'refresh_token';
  static const _keyRole = 'user_role';
  static const _keyUserId = 'user_id';
  static const _keyName = 'display_name';
  static const _keyUid = 'unique_user_id';
  static const _keys = [
    _keyAccess,
    _keyRefresh,
    _keyRole,
    _keyUserId,
    _keyName,
    _keyUid,
  ];

  Future<void> saveTokens({
    required String accessToken,
    required String refreshToken,
    required String role,
    required String userId,
    String? displayName,
    String? uniqueUserId,
  }) async {
    if (kIsWeb) {
      final prefs = await SharedPreferences.getInstance();
      await Future.wait([
        prefs.setString(_keyAccess, accessToken),
        prefs.setString(_keyRefresh, refreshToken),
        prefs.setString(_keyRole, role),
        prefs.setString(_keyUserId, userId),
        if (displayName != null) prefs.setString(_keyName, displayName),
        if (uniqueUserId != null) prefs.setString(_keyUid, uniqueUserId),
      ]);
      return;
    }

    await Future.wait([
      _storage.write(key: _keyAccess, value: accessToken),
      _storage.write(key: _keyRefresh, value: refreshToken),
      _storage.write(key: _keyRole, value: role),
      _storage.write(key: _keyUserId, value: userId),
      if (displayName != null)
        _storage.write(key: _keyName, value: displayName),
      if (uniqueUserId != null)
        _storage.write(key: _keyUid, value: uniqueUserId),
    ]);
  }

  Future<String?> getAccessToken() async => _read(_keyAccess);
  Future<String?> getRefreshToken() async => _read(_keyRefresh);
  Future<String?> getUserRole() async => _read(_keyRole);
  Future<String?> getUserId() async => _read(_keyUserId);
  Future<String?> getDisplayName() async => _read(_keyName);
  Future<String?> getUniqueUserId() async => _read(_keyUid);

  Future<void> clearAll() async {
    if (kIsWeb) {
      final prefs = await SharedPreferences.getInstance();
      await Future.wait(_keys.map(prefs.remove));
      return;
    }
    await _storage.deleteAll();
  }

  Future<String?> _read(String key) async {
    if (kIsWeb) {
      final prefs = await SharedPreferences.getInstance();
      return prefs.getString(key);
    }
    try {
      return await _storage.read(key: key);
    } catch (_) {
      return null;
    }
  }
}
