/// Abstract contract for secure storage of API credentials.
///
/// [CredentialStore] provides a key/value interface for storing sensitive
/// values (API keys, tokens, secrets) in a secure location appropriate for
/// the platform. On Android/iOS this maps to the OS keystore; on desktop/web
/// it maps to an encrypted local store.
///
/// Concrete implementations:
/// - [InMemoryCredentialStore] — in-memory, non-persistent (for tests and fake mode)
/// - `SecureCredentialStore` — backed by `flutter_secure_storage` (production)
///
/// ## Well-known credential keys
///
/// Use the constants on [CredentialKeys] rather than raw strings to avoid
/// typos and ensure consistency across the codebase.
abstract class CredentialStore {
  /// Reads the credential stored under [key].
  ///
  /// Returns `null` if no value has been stored for [key].
  Future<String?> read(String key);

  /// Writes [value] under [key], replacing any existing value.
  Future<void> write(String key, String value);

  /// Deletes the credential stored under [key].
  ///
  /// No-op if [key] is not present.
  Future<void> delete(String key);

  /// Deletes all stored credentials.
  ///
  /// Use with caution — this clears all API keys and tokens.
  Future<void> deleteAll();

  /// Returns `true` if a non-null value is stored under [key].
  Future<bool> containsKey(String key);
}

/// Well-known keys for credentials stored in [CredentialStore].
///
/// Using these constants prevents typos and ensures all parts of the
/// codebase refer to the same storage keys.
abstract final class CredentialKeys {
  /// WooCommerce REST API consumer key (`ck_...`).
  static const String wcConsumerKey = 'kc.wc.consumer_key';

  /// WooCommerce REST API consumer secret (`cs_...`).
  static const String wcConsumerSecret = 'kc.wc.consumer_secret';

  /// WooCommerce site URL.
  static const String wcSiteUrl = 'kc.wc.site_url';

  /// Square API access token.
  static const String squareAccessToken = 'kc.square.access_token';

  /// Square location ID.
  static const String squareLocationId = 'kc.square.location_id';

  /// The currently authenticated user's session token (if applicable).
  static const String sessionToken = 'kc.auth.session_token';
}

/// An in-memory [CredentialStore] backed by a plain [Map].
///
/// Values are lost when the process exits. Suitable for tests and fake mode
/// where no real credentials need to be persisted.
class InMemoryCredentialStore implements CredentialStore {
  final Map<String, String> _store = {};

  @override
  Future<String?> read(String key) async => _store[key];

  @override
  Future<void> write(String key, String value) async => _store[key] = value;

  @override
  Future<void> delete(String key) async => _store.remove(key);

  @override
  Future<void> deleteAll() async => _store.clear();

  @override
  Future<bool> containsKey(String key) async => _store.containsKey(key);
}
