/// Helper pour l'authentification dans les tests d'intégration
library auth_helper;

import 'dart:convert';
import 'package:http/http.dart' as http;
import 'test_config.dart';

/// Helper pour gérer l'authentification dans les tests
class AuthHelper {
  final http.Client _client;
  String? _accessToken;
  String? _refreshToken;

  AuthHelper(this._client);

  /// Token d'accès actuel
  String? get accessToken => _accessToken;

  /// Authentifie un utilisateur via Keycloak Direct Access Grant
  ///
  /// Retourne true si l'authentification réussit, false sinon
  Future<bool> authenticate(String username, String password) async {
    final url = Uri.parse(
      '${TestConfig.keycloakUrl}/realms/${TestConfig.keycloakRealm}/protocol/openid-connect/token',
    );

    try {
      final response = await _client.post(
        url,
        headers: {'Content-Type': 'application/x-www-form-urlencoded'},
        body: {
          'grant_type': 'password',
          'client_id': TestConfig.keycloakClientId,
          'username': username,
          'password': password,
        },
      );

      if (response.statusCode == 200) {
        final data = json.decode(response.body);
        _accessToken = data['access_token'];
        _refreshToken = data['refresh_token'];

        if (TestConfig.enableDetailedLogs) {
          print('✅ Authentification réussie pour: $username');
        }
        return true;
      } else {
        if (TestConfig.enableDetailedLogs) {
          print('❌ Échec authentification: ${response.statusCode} - ${response.body}');
        }
        return false;
      }
    } catch (e) {
      if (TestConfig.enableDetailedLogs) {
        print('❌ Erreur authentification: $e');
      }
      return false;
    }
  }

  /// Authentifie l'utilisateur admin de test
  Future<bool> authenticateAsAdmin() async {
    return await authenticate(
      TestConfig.testAdminUsername,
      TestConfig.testAdminPassword,
    );
  }

  /// Authentifie l'utilisateur org admin de test
  Future<bool> authenticateAsOrgAdmin() async {
    return await authenticate(
      TestConfig.testOrgAdminUsername,
      TestConfig.testOrgAdminPassword,
    );
  }

  /// Rafraîchit le token d'accès
  Future<bool> refreshAccessToken() async {
    if (_refreshToken == null) {
      return false;
    }

    final url = Uri.parse(
      '${TestConfig.keycloakUrl}/realms/${TestConfig.keycloakRealm}/protocol/openid-connect/token',
    );

    try {
      final response = await _client.post(
        url,
        headers: {'Content-Type': 'application/x-www-form-urlencoded'},
        body: {
          'grant_type': 'refresh_token',
          'client_id': TestConfig.keycloakClientId,
          'refresh_token': _refreshToken!,
        },
      );

      if (response.statusCode == 200) {
        final data = json.decode(response.body);
        _accessToken = data['access_token'];
        _refreshToken = data['refresh_token'];
        return true;
      }
      return false;
    } catch (e) {
      if (TestConfig.enableDetailedLogs) {
        print('❌ Erreur rafraîchissement token: $e');
      }
      return false;
    }
  }

  /// Déconnecte l'utilisateur
  Future<void> logout() async {
    _accessToken = null;
    _refreshToken = null;

    if (TestConfig.enableDetailedLogs) {
      print('🔓 Déconnexion effectuée');
    }
  }

  /// Retourne les headers HTTP avec authentification
  Map<String, String> getAuthHeaders() {
    return {
      'Content-Type': 'application/json',
      'Accept': 'application/json',
      if (_accessToken != null) 'Authorization': 'Bearer $_accessToken',
    };
  }
}
