import 'package:dio/dio.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:recolecta_app/core/storage/secure_storage.dart';

final apiServiceProvider = Provider<ApiService>((ref) {
  return ApiService(ref);
});

class ApiService {
  final Ref _ref;
  final Dio _dio = Dio(
    BaseOptions(
      baseUrl: 'http://localhost:8000', // O la URL de tu backend
    ),
  );

  ApiService(this._ref) {
    _dio.interceptors.add(
      InterceptorsWrapper(
        onRequest: (options, handler) async {
          final token = await _ref
              .read(secureStorageProvider)
              .read(key: 'auth_token');
          if (token != null) {
            options.headers['Authorization'] = 'Bearer $token';
          }
          return handler.next(options);
        },
      ),
    );
  }

  Future<void> updateUser(Map<String, dynamic> data) async {
    try {
      await _dio.patch('/users/me', data: data);
    } on DioException catch (e) {
      throw e.response?.data['detail'] ?? 'Error de red';
    }
  }
}
