import 'package:flutter_secure_storage/flutter_secure_storage.dart';

import 'token_storage.dart';

/// 안전한 스토리지에 저장할 액세스 토큰 키.
const _kAccessTokenKey = 'access_token';

/// 안전한 스토리지에 저장할 리프레시 토큰 키.
const _kRefreshTokenKey = 'refresh_token';

/// 모바일/데스크톱에서 [FlutterSecureStorage]를 사용하는 토큰 스토리지를 생성한다.
TokenStorage buildTokenStorage() {
  const storage = FlutterSecureStorage(
    aOptions: AndroidOptions(encryptedSharedPreferences: true),
    iOptions: IOSOptions(accessibility: KeychainAccessibility.first_unlock),
    mOptions: MacOsOptions(),
    wOptions: WindowsOptions(),
    lOptions: LinuxOptions(),
  );
  return _SecureTokenStorage(storage);
}

/// [FlutterSecureStorage] 기반 토큰 스토리지 구현체.
class _SecureTokenStorage implements TokenStorage {
  const _SecureTokenStorage(this._storage);

  final FlutterSecureStorage _storage;

  @override
  Future<void> clear() async {
    await _storage.delete(key: _kAccessTokenKey);
    await _storage.delete(key: _kRefreshTokenKey);
  }

  @override
  Future<String?> readAccessToken() => _storage.read(key: _kAccessTokenKey);

  @override
  Future<String?> readRefreshToken() => _storage.read(key: _kRefreshTokenKey);

  @override
  Future<void> writeAccessToken(String? token) async {
    if (token == null || token.isEmpty) {
      await _storage.delete(key: _kAccessTokenKey);
      return;
    }
    await _storage.write(key: _kAccessTokenKey, value: token);
  }

  @override
  Future<void> writeRefreshToken(String? token) async {
    if (token == null || token.isEmpty) {
      await _storage.delete(key: _kRefreshTokenKey);
      return;
    }
    await _storage.write(key: _kRefreshTokenKey, value: token);
  }
}
