import 'package:dio/dio.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:recording_tool/app/config/app_config.dart';
import 'package:recording_tool/core/network/api_client.dart';
import 'package:recording_tool/core/network/app_dio.dart';
import 'package:recording_tool/core/network/header_interceptor.dart';
import 'package:recording_tool/core/network/offline_queue/offline_queue_interceptor.dart';
import 'package:recording_tool/core/network/providers/network_providers.dart';
import 'package:recording_tool/core/network/providers/offline_queue_providers.dart';

bool _dioConfigured = false;

final dioProvider = Provider<Dio>((ref) {
  final dio = AppDio.instance;

  if (!_dioConfigured) {
    _dioConfigured = true;
    dio.interceptors.add(HeaderInterceptor());

    final monitor = ref.read(networkMonitorProvider);
    final queueManager = ref.read(offlineQueueManagerProvider);
    dio.interceptors.add(
      OfflineQueueInterceptor(
        monitor: monitor,
        manager: queueManager,
        enabled: false,
      ),
    );

    if (AppConfig.current.enableNetworkLog) {
      dio.interceptors.add(
        LogInterceptor(requestBody: true, responseBody: true),
      );
    }
  }

  return dio;
});

final apiClientProvider = Provider<ApiClient>((ref) {
  return ApiClient(ref.watch(dioProvider));
});
