import '../models/bo/login_model.dart';
import '../models/bo/user_model.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<LoginModel> login(String phone, String smsCode) async {
    final result = await _authRepository.login(phone, smsCode);

    if (result.success && result.data != null) {
      final loginModel = result.data!;
      if (loginModel.accessToken != null &&
          loginModel.accessToken!.isNotEmpty) {
        await _storageService.saveToken(
          loginModel.accessToken!,
          expiryHours: Constants.tokenExpiryHours,
        );
      }
      if (loginModel.refreshToken != null &&
          loginModel.refreshToken!.isNotEmpty) {
        await _storageService.saveRefreshToken(loginModel.refreshToken!);
      }
      if (loginModel.user != null) {
        await _storageService.saveUserInfo(loginModel.user!);
      }
      return loginModel;
    }
    throw Exception(result.msg);
  }

  Future<UserModel> 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<UserModel?> 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();
  }
}
