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<bool> login(String username, String password) async {
    final result = await _authRepository.login({
      'username': username,
      'password': password,
    });

    if (result.success) {
      final data = result.data;
      if (data is Map<String, dynamic> && data.containsKey('token')) {
        final token = data['token'] as String?;
        if (token != null && token.isNotEmpty) {
          await _storageService.saveToken(
            token,
            expiryHours: Constants.tokenExpiryHours,
          );
          return true;
        }
      }
    }

    return false;
  }

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