import 'package:dio/dio.dart';
import 'package:fancy_dio_inspector/fancy_dio_inspector.dart';
import 'package:flutter/foundation.dart';
import 'package:hooks_riverpod/hooks_riverpod.dart';
import 'package:riverpod_annotation/riverpod_annotation.dart';

import '../config/app_config.dart';
import 'auth_interceptor.dart';
import 'kratos_error_interceptor.dart';

part 'dio_provider.g.dart';

const _protobufContentType = 'application/x-protobuf';

@Riverpod(keepAlive: true)
AppConfig appConfig(Ref ref) => AppConfig.fromEnvironment();

@Riverpod(keepAlive: true)
Dio dio(Ref ref) {
  final config = ref.watch(appConfigProvider);
  final d = Dio(
    BaseOptions(
      baseUrl: config.apiBaseUrl,
      connectTimeout: const Duration(seconds: 15),
      receiveTimeout: const Duration(seconds: 30),
      responseType: ResponseType.bytes,
      contentType: _protobufContentType,
      headers: const {
        'Accept': _protobufContentType,
        'Content-Type': _protobufContentType,
      },
    ),
  );
  d.interceptors.add(AuthInterceptor());
  d.interceptors.add(KratosErrorInterceptor());
  if (!kReleaseMode) {
    d.interceptors.add(LogInterceptor(requestBody: false, responseBody: false));
  }
  d.interceptors.add(FancyDioInterceptor());
  return d;
}
