import 'package:dio/dio.dart';
import 'package:flutter/foundation.dart';
import 'package:pretty_dio_logger/pretty_dio_logger.dart';

final ApiService apiService = ApiService();

class ApiService {
  final keycloak = 'https://keycloak.liara.run/';
  final clientID = 'frontend';
  final realm = 'lba';

  late Dio _dio;

  void setAuthToken(String token) {
    _dio.options.headers['Authorization'] = 'Bearer $token';
  }

  ApiService() {
    _dio = Dio(
      BaseOptions(
        baseUrl:
            '$keycloak/$realm/protocol/openid-connect', // 🔹 Set your API base URL
        connectTimeout: const Duration(seconds: 10), // Timeout settings
        receiveTimeout: const Duration(seconds: 10),
        headers: {
          'Accept': 'application/json',
          'Content-Type': 'application/json',
        },
      ),
    )..interceptors.add(PrettyDioLogger(
        enabled: kDebugMode,
      ));
  }

  /// 🔹 Handle GET requests
  Future<dynamic> get(String endpoint, {Map<String, dynamic>? params}) async {
    try {
      Response response = await _dio.get(endpoint, queryParameters: params);
      return response.data;
    } catch (e) {
      _handleError(e);
    }
  }

  /// 🔹 Handle POST requests
  Future<dynamic> post(String endpoint, {dynamic data}) async {
    try {
      Response response = await _dio.post(endpoint, data: data);
      return response.data;
    } catch (e) {
      _handleError(e);
    }
  }

  /// 🔹 Handle PUT requests
  Future<dynamic> put(String endpoint, {dynamic data}) async {
    try {
      Response response = await _dio.put(endpoint, data: data);
      return response.data;
    } catch (e) {
      _handleError(e);
    }
  }

  /// 🔹 Handle DELETE requests
  Future<dynamic> delete(String endpoint, {dynamic data}) async {
    try {
      Response response = await _dio.delete(endpoint, data: data);
      return response.data;
    } catch (e) {
      _handleError(e);
    }
  }

  /// 🔹 Error handling
  void _handleError(dynamic error) {
    if (error is DioException) {
      switch (error.type) {
        case DioExceptionType.connectionTimeout:
          throw Exception("Connection timeout, please try again.");
        case DioExceptionType.receiveTimeout:
          throw Exception("Receive timeout, please try again.");
        case DioExceptionType.badResponse:
          throw Exception("Server error: ${error.response?.statusCode}");
        case DioExceptionType.cancel:
          throw Exception("Request canceled.");
        default:
          throw Exception("Unexpected error occurred.");
      }
    } else {
      throw Exception("Unknown error: $error");
    }
  }
}
