import 'dart:convert'; import 'dart:io'; import 'package:http/http.dart' as http; import '../config/intra_config.dart'; import 'intra_api_exception.dart'; import 'intra_auth_service.dart'; class IntraUserService { IntraUserService._(); static final IntraUserService instance = IntraUserService._(); final IntraAuthService _auth = IntraAuthService.instance; /// Recherche par login — réutilise le token OAuth (pas de nouvel OAuth). Future> fetchUserByLogin(String login) async { final trimmed = login.trim(); if (trimmed.isEmpty) { throw const IntraApiErrorException('Saisis un login'); } if (!_auth.isAuthenticated) { throw const IntraNotAuthenticatedException(); } final uri = Uri.parse('${IntraConfig.apiBaseUrl}/users').replace( queryParameters: {'filter[login]': trimmed}, ); try { final response = await http.get(uri, headers: _auth.authHeaders()); return _parseUserListResponse(response, trimmed); } on IntraApiException { rethrow; } on SocketException { throw const IntraNetworkException(); } on http.ClientException { throw const IntraNetworkException(); } } Map _parseUserListResponse( http.Response response, String login, ) { if (response.statusCode == 401) { throw const IntraUnauthorizedException(); } if (response.statusCode != 200) { throw IntraApiErrorException( 'Erreur API (${response.statusCode})', ); } final decoded = jsonDecode(response.body); if (decoded is! List) { throw IntraApiErrorException('Réponse API inattendue'); } if (decoded.isEmpty) { throw const IntraUserNotFoundException(); } final user = decoded.first; if (user is! Map) { throw IntraApiErrorException('Réponse API inattendue'); } return user; } }