// token_store.dart — JWT 令牌安全持久化（flutter_secure_storage 封装）
import 'package:flutter_secure_storage/flutter_secure_storage.dart';

class TokenStore {
  const TokenStore({FlutterSecureStorage? storage})
      : _storage = storage ?? const FlutterSecureStorage(
          // macOS 用文件式 keychain，避免未签名 app 缺 keychain-access-groups
          // entitlement 时 write 报 -34018。
          mOptions: MacOsOptions(useDataProtectionKeyChain: false),
        );

  final FlutterSecureStorage _storage;

  static const _kAccess = 'pangolin_access_token';
  static const _kRefresh = 'pangolin_refresh_token';
  static const _kOnboarded = 'pangolin_onboarded';
  static const _kLastEmail = 'pangolin_last_email';

  Future<void> saveTokens({
    required String access,
    required String refresh,
  }) async {
    await _storage.write(key: _kAccess, value: access);
    await _storage.write(key: _kRefresh, value: refresh);
  }

  Future<String?> loadAccessToken() => _storage.read(key: _kAccess);
  Future<String?> loadRefreshToken() => _storage.read(key: _kRefresh);

  Future<void> clear() async {
    await _storage.delete(key: _kAccess);
    await _storage.delete(key: _kRefresh);
  }

  // 首次引导标记:引导页只在第一次看(看完置位,后续登录直接进主界面)。
  Future<void> markOnboarded() => _storage.write(key: _kOnboarded, value: '1');
  Future<bool> isOnboarded() async => (await _storage.read(key: _kOnboarded)) == '1';

  // 记住上次登录邮箱(登录页预填;退出登录不清除)。
  Future<void> saveLastEmail(String email) => _storage.write(key: _kLastEmail, value: email);
  Future<String?> loadLastEmail() => _storage.read(key: _kLastEmail);
}
