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'; import 'intra_http.dart'; /// Recherche d'un login via `GET /v2/users?filter[login]=` (même token OAuth que le profil). 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 intraApiGet(uri, auth: _auth); 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, ) { ensureIntraOk(response); 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; } }