import 'package:dio/dio.dart';

import '../config.dart';
import '../storage/token_storage.dart';

/// لایه‌ی پایه‌ی شبکه: یک Dio با baseUrl، تزریق خودکار توکن Bearer و
/// validateStatus باز (تا کدهای خطا throw نشوند و در repository بررسی شوند).
class ApiProviderImp {
  final Dio dio;

  ApiProviderImp(TokenStorage storage)
      : dio = Dio(BaseOptions(
          baseUrl: AppConfig.apiUrl,
          connectTimeout: const Duration(seconds: 10),
          receiveTimeout: const Duration(seconds: 15),
          headers: {'Accept': 'application/json'},
          validateStatus: (_) => true,
        )) {
    dio.interceptors.add(InterceptorsWrapper(
      onRequest: (options, handler) async {
        final token = await storage.read();
        if (token != null && token.isNotEmpty) {
          options.headers['Authorization'] = 'Bearer $token';
        }
        handler.next(options);
      },
    ));
  }

  Future<Response> get(String path, {Map<String, dynamic>? query}) =>
      dio.get(path, queryParameters: query);

  Future<Response> post(String path, {Object? body}) =>
      dio.post(path, data: body);

  Future<Response> put(String path, {Object? body}) =>
      dio.put(path, data: body);

  Future<Response> delete(String path, {Object? body}) =>
      dio.delete(path, data: body);
}
