part of '../app/app.dart';

class SessionStore {
  static const _tokenKey = 'mylis_token';
  static const _baseUrlKey = 'mylis_base_url';
  static const _usernameKey = 'mylis_username';
  static const _passwordKey = 'mylis_password';

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

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

  static Future<SessionData> session() async {
    final prefs = await SharedPreferences.getInstance();
    return SessionData(
      token: prefs.getString(_tokenKey),
      baseUrl: prefs.getString(_baseUrlKey) ?? kDefaultBaseUrl,
      username: prefs.getString(_usernameKey),
      password: prefs.getString(_passwordKey),
    );
  }

  static Future<void> saveToken(String token) async {
    final prefs = await SharedPreferences.getInstance();
    await prefs.setString(_tokenKey, token);
  }

  static Future<void> saveLogin({
    required String baseUrl,
    required String token,
    required String username,
    required String password,
  }) async {
    final prefs = await SharedPreferences.getInstance();
    await prefs.setString(_baseUrlKey, normalizeBaseUrl(baseUrl));
    await prefs.setString(_tokenKey, token);
    await prefs.setString(_usernameKey, username);
    await prefs.setString(_passwordKey, password);
  }

  static Future<StoredCredentials?> credentials() async {
    final prefs = await SharedPreferences.getInstance();
    final username = prefs.getString(_usernameKey);
    final password = prefs.getString(_passwordKey);
    if (username == null ||
        username.trim().isEmpty ||
        password == null ||
        password.isEmpty) {
      return null;
    }
    return StoredCredentials(username: username, password: password);
  }

  static Future<void> saveBaseUrl(String baseUrl) async {
    final prefs = await SharedPreferences.getInstance();
    await prefs.setString(_baseUrlKey, normalizeBaseUrl(baseUrl));
  }

  static Future<void> clear() async {
    final prefs = await SharedPreferences.getInstance();
    await prefs.remove(_tokenKey);
  }
}

class SessionData {
  const SessionData({
    this.token,
    this.baseUrl = kDefaultBaseUrl,
    this.username,
    this.password,
  });

  final String? token;
  final String baseUrl;
  final String? username;
  final String? password;
}

class StoredCredentials {
  const StoredCredentials({required this.username, required this.password});

  final String username;
  final String password;
}

String normalizeBaseUrl(String value) {
  var url = value.trim();
  if (url.isEmpty) {
    return kDefaultBaseUrl;
  }
  if (!url.startsWith('http://') && !url.startsWith('https://')) {
    url = 'https://$url';
  }
  return url.replaceAll(RegExp(r'/+$'), '');
}
