/// Authentication Local Data Source
///
/// Handles secure local storage of authentication session data.
/// Uses flutter_secure_storage for SID and CSRF token (encrypted).
library;

import 'package:flutter_secure_storage/flutter_secure_storage.dart';
import 'package:worker/features/auth/data/models/auth_session_model.dart';

/// Authentication Local Data Source
///
/// Manages session data (SID, CSRF token) using secure storage.
/// Session tokens are stored encrypted on device.
class AuthLocalDataSource {
  final FlutterSecureStorage _secureStorage;

  /// Secure storage keys
  static const String _sidKey = 'auth_session_sid';
  static const String _csrfTokenKey = 'auth_session_csrf_token';
  static const String _fullNameKey = 'auth_session_full_name';
  static const String _createdAtKey = 'auth_session_created_at';
  static const String _appsKey = 'auth_session_apps';
  static const String _rememberMeKey = 'auth_remember_me';

  AuthLocalDataSource(this._secureStorage);

  /// Save session data securely
  ///
  /// Stores SID, CSRF token, and user info in encrypted storage.
  Future<void> saveSession(SessionData session) async {
    await _secureStorage.write(key: _sidKey, value: session.sid);
    await _secureStorage.write(key: _csrfTokenKey, value: session.csrfToken);
    await _secureStorage.write(key: _fullNameKey, value: session.fullName);
    await _secureStorage.write(
      key: _createdAtKey,
      value: session.createdAt.toIso8601String(),
    );

    // Store apps as JSON string if available
    if (session.apps != null && session.apps!.isNotEmpty) {
      final appsJson = session.apps!.map((app) => app.toJson()).toList();
      // Convert to JSON string for storage
      await _secureStorage.write(key: _appsKey, value: appsJson.toString());
    }
  }

  /// Get stored session data
  ///
  /// Returns null if no session is stored.
  Future<SessionData?> getSession() async {
    final sid = await _secureStorage.read(key: _sidKey);
    final csrfToken = await _secureStorage.read(key: _csrfTokenKey);
    final fullName = await _secureStorage.read(key: _fullNameKey);
    final createdAtStr = await _secureStorage.read(key: _createdAtKey);

    if (sid == null || csrfToken == null || fullName == null) {
      return null;
    }

    final createdAt = createdAtStr != null
        ? DateTime.tryParse(createdAtStr) ?? DateTime.now()
        : DateTime.now();

    // TODO: Parse apps from JSON string if needed
    // For now, apps are optional

    return SessionData(
      sid: sid,
      csrfToken: csrfToken,
      fullName: fullName,
      createdAt: createdAt,
      apps: null, // TODO: Parse from stored JSON if needed
    );
  }

  /// Get SID (Session ID)
  ///
  /// Returns null if not logged in.
  Future<String?> getSid() async {
    return await _secureStorage.read(key: _sidKey);
  }

  /// Get CSRF Token
  ///
  /// Returns null if not logged in.
  Future<String?> getCsrfToken() async {
    return await _secureStorage.read(key: _csrfTokenKey);
  }

  /// Get Full Name
  ///
  /// Returns null if not logged in.
  Future<String?> getFullName() async {
    return await _secureStorage.read(key: _fullNameKey);
  }

  /// Check if user has valid session
  ///
  /// Returns true if SID and CSRF token are present.
  Future<bool> hasValidSession() async {
    final sid = await getSid();
    final csrfToken = await getCsrfToken();
    return sid != null && csrfToken != null;
  }

  /// Save "Remember Me" preference
  ///
  /// If true, user session will be restored on next app launch.
  Future<void> saveRememberMe(bool rememberMe) async {
    await _secureStorage.write(
      key: _rememberMeKey,
      value: rememberMe.toString(),
    );
  }

  /// Get "Remember Me" preference
  ///
  /// Returns true if user wants to be remembered, false otherwise.
  Future<bool> getRememberMe() async {
    final value = await _secureStorage.read(key: _rememberMeKey);
    return value == 'true';
  }

  /// Clear session data
  ///
  /// Called during logout to remove all session information including rememberMe.
  Future<void> clearSession() async {
    // Clear all session data including rememberMe
    await _secureStorage.delete(key: _sidKey);
    await _secureStorage.delete(key: _csrfTokenKey);
    await _secureStorage.delete(key: _fullNameKey);
    await _secureStorage.delete(key: _createdAtKey);
    await _secureStorage.delete(key: _appsKey);
    await _secureStorage.delete(key: _rememberMeKey);
  }

  /// Clear all authentication data including remember me
  ///
  /// Complete cleanup of all stored auth data.
  Future<void> clearAll() async {
    await _secureStorage.delete(key: _sidKey);
    await _secureStorage.delete(key: _csrfTokenKey);
    await _secureStorage.delete(key: _fullNameKey);
    await _secureStorage.delete(key: _createdAtKey);
    await _secureStorage.delete(key: _appsKey);
    await _secureStorage.delete(key: _rememberMeKey);
  }
}
