import '../models/bo/login_bo.dart';
import '../models/bo/user_info_bo.dart';
import '../repositories/auth_repository.dart';
import '../utils/constants.dart';
import '../utils/storage/storage_service.dart';

class AuthService {
  final AuthRepository _authRepository;
  final StorageService _storageService;

  AuthService({
    required AuthRepository authRepository,
    required StorageService storageService,
  })  : _authRepository = authRepository,
        _storageService = storageService;

  Future<LoginBO> login(String username, String password) async {
    final result = await _authRepository.login({
      'username': username,
      'password': password,
    });

    if (result.success && result.data != null) {
      final loginBO = result.data!;
      if (loginBO.accessToken != null && loginBO.accessToken!.isNotEmpty) {
        await _storageService.saveToken(
          loginBO.accessToken!,
          expiryHours: Constants.tokenExpiryHours,
        );
      }
      if (loginBO.clientId != null && loginBO.clientId!.isNotEmpty) {
        await _storageService.saveClientId(loginBO.clientId!);
      }
      return loginBO;
    }
    throw Exception(result.msg);
  }

  Future<UserInfoBO> getUserInfo() async {
    final result = await _authRepository.getUserInfo();
    if (result.success && result.data != null) {
      final userInfo = result.data!;
      await _storageService.saveUserInfo(userInfo);
      return userInfo;
    }
    throw Exception(result.msg);
  }

  Future<UserInfoBO?> getStoredUserInfo() async {
    return _storageService.getUserInfo();
  }

  Future<void> logout() async {
    final result = await _authRepository.logout();
    if (!result.success) {
      throw Exception(result.msg);
    }
  }

  Future<bool> isTokenExpired() async {
    return _storageService.isTokenExpired();
  }
}