// lib/core/storage/token_storage.dart

import 'package:shared_preferences/shared_preferences.dart';

class TokenStorage {
  static const _tokenKey = "auth_token";
  static const _authUsernameKey = "auth_username"; // new key used for backend identity
  static const _oldUsernameKey = "username"; // old key (may have been used for UI or auth)
  static const _displayNameKey = "display_name"; // UI display name

  /// Save token and backend username.
  /// Will save `auth_username` always. It will only overwrite the old `username` key
  /// if that key is missing or already looks like an email (avoid overwriting user display names).
  static Future<void> saveToken(String token, String username) async {
    final prefs = await SharedPreferences.getInstance();
    await prefs.setString(_tokenKey, token);
    await prefs.setString(_authUsernameKey, username);

    final oldVal = prefs.getString(_oldUsernameKey);
    // If old key not present OR old value looks like an email (so it's probably the backend username),
    // keep it in sync. Do not overwrite if it's a display name.
    if (oldVal == null || oldVal.contains('@')) {
      await prefs.setString(_oldUsernameKey, username);
    }
  }

  static Future<String?> getToken() async {
    final prefs = await SharedPreferences.getInstance();
    return prefs.getString(_tokenKey);
  }

  /// Return backend username (auth identity).
  /// Tries new key first, falls back to old key for compatibility.
  static Future<String?> getUsername() async {
    final prefs = await SharedPreferences.getInstance();
    final auth = prefs.getString(_authUsernameKey);
    if (auth != null && auth.isNotEmpty) return auth;
    // fallback (older apps used 'username' key)
    final old = prefs.getString(_oldUsernameKey);
    return old;
  }

  /// Helper to read display name (UI)
  static Future<String?> getDisplayName() async {
    final prefs = await SharedPreferences.getInstance();
    return prefs.getString(_displayNameKey);
  }

  /// Save display name for UI (do NOT use this key for backend authentication)
  static Future<void> saveDisplayName(String displayName) async {
    final prefs = await SharedPreferences.getInstance();
    await prefs.setString(_displayNameKey, displayName);
  }

  static Future<void> clear() async {
    final prefs = await SharedPreferences.getInstance();
    // Intentionally clear only auth-related keys (keeps user display name if you want)
    await prefs.remove(_tokenKey);
    await prefs.remove(_authUsernameKey);
    // do NOT remove _oldUsernameKey or _displayNameKey automatically to avoid losing UI settings
  }
}
