import 'package:kmobile/api/services/user_service.dart';

import '../../api/services/auth_service.dart';
import '../../features/auth/models/auth_token.dart';
import '../../features/auth/models/auth_credentials.dart';
import '../../data/models/user.dart';
import '../../security/secure_storage.dart';

class AuthRepository {
  final AuthService _authService;
  final UserService _userService;
  final SecureStorage _secureStorage;

  static const _accessTokenKey = 'access_token';
  static const _tokenExpiryKey = 'token_expiry';
  static const _tncKey = 'tnc';

  AuthRepository(this._authService, this._userService, this._secureStorage);

  Future<(List<User>, AuthToken)> login(
      String customerNo, String password) async {
    // Create credentials and call service
    final credentials =
        AuthCredentials(customerNo: customerNo, password: password);
    final authToken = await _authService.login(credentials);

    // Save token securely
    await _saveAuthToken(authToken);

    // Get and save user profile
    final users = await _userService.getUserDetails();
    return (users, authToken);
  }

  Future<bool> isLoggedIn() async {
    final token = await _getAuthToken();
    return token != null && !token.isExpired;
  }

  Future<String?> getAccessToken() async {
    final token = await _getAuthToken();
    if (token == null) return null;

    return token.accessToken;
  }

  // Private helper methods
  Future<void> _saveAuthToken(AuthToken token) async {
    await _secureStorage.write(_accessTokenKey, token.accessToken);
    await _secureStorage.write(
        _tokenExpiryKey, token.expiresAt.toIso8601String());
    await _secureStorage.write(_tncKey, token.tnc.toString());
  }

  Future<void> clearAuthTokens() async {
    await _secureStorage.deleteAll();
  }

  Future<AuthToken?> _getAuthToken() async {
    final accessToken = await _secureStorage.read(_accessTokenKey);
    final expiryString = await _secureStorage.read(_tokenExpiryKey);
    final tncString = await _secureStorage.read(_tncKey);

    if (accessToken != null && expiryString != null) {
      final authToken = AuthToken(
        accessToken: accessToken,
        expiresAt: DateTime.parse(expiryString),
        tnc:
            tncString == 'true', // Parse 'true' string to true, otherwise false
      );
      return authToken;
    }
    return null;
  }

  Future<void> acceptTnc() async {
    // This method calls the setTncFlag function
    try {
      await _authService.setTncflag();
    } catch (e) {
      // Handle or rethrow the error as needed
      print('Error setting TNC flag: $e');
      rethrow;
    }
  }
}
