import 'package:dio/dio.dart';
import 'auth_storage.dart';

const String baseUrl = 'https://jambo.gmapps.online/public';
// const String baseUrl = 'https://legal-pleasant-prawn.ngrok-free.app/jambo/public';

Dio createApiClient(Function() onUnauthorized) {
  final dio = Dio(BaseOptions(
    baseUrl: baseUrl,
    connectTimeout: const Duration(seconds: 10),
    receiveTimeout: const Duration(seconds: 10),
    headers: {'Accept': 'application/json', 'Content-Type': 'application/json'},
  ));

  dio.interceptors.add(InterceptorsWrapper(
    onRequest: (options, handler) async {
      final token = await AuthStorage.getToken();
      if (token != null && token.isNotEmpty) {
        options.headers['Authorization'] = 'Bearer $token';
      }
      return handler.next(options);
    },
    onError: (error, handler) async {
      if (error.response?.statusCode == 401) {
        await AuthStorage.clearToken();
        onUnauthorized();
      }
      return handler.next(error);
    },
  ));

  return dio;
}
