import 'package:flutter_secure_storage/flutter_secure_storage.dart';

class StorageService {
  static const String _keyToken = 'auth_token';
  static const String _keyTokenExpiry = 'auth_token_expiry';
  static const String _keyRememberUsername = 'remember_username';
  static const String _keyRememberPassword = 'remember_password';
  static const String _keyRememberEnabled = 'remember_enabled';

  final FlutterSecureStorage _storage = const FlutterSecureStorage(
    aOptions: AndroidOptions(
      encryptedSharedPreferences: true,
    ),
  );

  // ==================== Token 相关 ====================

  Future<void> saveToken(String token, {int expiryHours = 24}) async {
    await _storage.write(key: _keyToken, value: token);
    final expiryTime =
        DateTime.now().add(Duration(hours: expiryHours)).millisecondsSinceEpoch;
    await _storage.write(key: _keyTokenExpiry, value: expiryTime.toString());
  }

  Future<String?> getToken() async {
    return await _storage.read(key: _keyToken);
  }

  Future<int?> getTokenExpiry() async {
    final value = await _storage.read(key: _keyTokenExpiry);
    if (value == null) return null;
    return int.tryParse(value);
  }

  Future<bool> isTokenExpired() async {
    final expiry = await getTokenExpiry();
    if (expiry == null) return false;
    return DateTime.now().millisecondsSinceEpoch > expiry;
  }

  Future<void> deleteToken() async {
    await _storage.delete(key: _keyToken);
    await _storage.delete(key: _keyTokenExpiry);
  }

  Future<bool> hasToken() async {
    final token = await getToken();
    return token != null && token.isNotEmpty;
  }

  // ==================== 记住密码相关 ====================

  Future<void> saveRememberCredentials({
    required String username,
    required String password,
  }) async {
    await _storage.write(key: _keyRememberUsername, value: username);
    await _storage.write(key: _keyRememberPassword, value: password);
    await _storage.write(key: _keyRememberEnabled, value: 'true');
  }

  Future<Map<String, String?>> getRememberCredentials() async {
    final enabled = await _storage.read(key: _keyRememberEnabled);
    if (enabled != 'true') {
      return {'username': null, 'password': null};
    }
    final username = await _storage.read(key: _keyRememberUsername);
    final password = await _storage.read(key: _keyRememberPassword);
    return {'username': username, 'password': password};
  }

  Future<void> clearRememberCredentials() async {
    await _storage.delete(key: _keyRememberUsername);
    await _storage.delete(key: _keyRememberPassword);
    await _storage.delete(key: _keyRememberEnabled);
  }

  // ==================== 清空所有数据 ====================

  Future<void> clearAll() async {
    await _storage.deleteAll();
  }
}
