import 'package:shared_preferences/shared_preferences.dart';

import '../../contracts/trakt/trakt_token.dart';


class TraktTokenStore {
  static const keyAccessToken = 'smplayer.trakt_access_token';
  static const keyRefreshToken = 'smplayer.trakt_refresh_token';
  static const keyExpiresIn = 'smplayer.trakt_expires_in';
  static const keyCreatedAt = 'smplayer.trakt_created_at';

  Future<SharedPreferences> _prefs() => SharedPreferences.getInstance();


  Future<TraktToken?> read() async {
    final p = await _prefs();
    final access = p.getString(keyAccessToken)?.trim() ?? '';
    if (access.isEmpty) return null;
    return TraktToken(
      accessToken: access,
      refreshToken: p.getString(keyRefreshToken)?.trim() ?? '',
      expiresIn: p.getInt(keyExpiresIn) ?? 0,
      createdAt: p.getInt(keyCreatedAt) ?? 0,
    );
  }

  Future<void> write(TraktToken token) async {
    final p = await _prefs();
    await Future.wait<Object?>([
      p.setString(keyAccessToken, token.accessToken),
      p.setString(keyRefreshToken, token.refreshToken),
      p.setInt(keyExpiresIn, token.expiresIn),
      p.setInt(keyCreatedAt, token.createdAt),
    ]);
  }

  Future<void> clear() async {
    final p = await _prefs();
    await Future.wait<Object?>([
      p.remove(keyAccessToken),
      p.remove(keyRefreshToken),
      p.remove(keyExpiresIn),
      p.remove(keyCreatedAt),
    ]);
  }
}
