import 'package:flutter_secure_storage/flutter_secure_storage.dart';

import '../../application/application.dart';

final class SecureStorageAuthTokenStore implements AuthTokenStore {
  const SecureStorageAuthTokenStore({
    FlutterSecureStorage storage = const FlutterSecureStorage(),
  }) : _storage = storage;

  static const _tokenKey = 'gametime.auth.token';
  static const _expiresAtKey = 'gametime.auth.expiresAt';

  final FlutterSecureStorage _storage;

  @override
  Future<void> saveToken(String token, DateTime expiresAt) async {
    await _storage.write(key: _tokenKey, value: token);
    await _storage.write(
      key: _expiresAtKey,
      value: expiresAt.toUtc().toIso8601String(),
    );
  }

  @override
  Future<String?> readToken() async {
    final token = await _storage.read(key: _tokenKey);
    final expiresAtValue = await _storage.read(key: _expiresAtKey);
    if (token == null || expiresAtValue == null) {
      return token;
    }
    final expiresAt = DateTime.tryParse(expiresAtValue)?.toUtc();
    if (expiresAt != null && !expiresAt.isAfter(DateTime.now().toUtc())) {
      await clearToken();
      return null;
    }
    return token;
  }

  @override
  Future<void> clearToken() async {
    await _storage.delete(key: _tokenKey);
    await _storage.delete(key: _expiresAtKey);
  }
}
