import 'package:dio/dio.dart';
import '../../../../core/config/api_endpoints.dart';
import '../models/standing_order_model.dart';

/// Remote datasource for standing order CRUD operations.
class StandingOrdersDatasource {
  final Dio _dio;

  StandingOrdersDatasource(this._dio);

  /// Fetches all standing orders.
  Future<List<StandingOrderModel>> fetchAll() async {
    final response = await _dio.get(ApiEndpoints.standingOrders);

    final data = response.data;
    List<dynamic> items;

    if (data is List) {
      items = data;
    } else if (data is Map && data.containsKey('items')) {
      items = data['items'] as List;
    } else {
      items = [];
    }

    return items
        .map((item) =>
            StandingOrderModel.fromJson(item as Map<String, dynamic>))
        .toList();
  }

  /// Fetches a single standing order by ID.
  Future<StandingOrderModel> fetchById(String id) async {
    final response = await _dio.get('${ApiEndpoints.standingOrders}/$id');
    return StandingOrderModel.fromJson(
        response.data as Map<String, dynamic>);
  }

  /// Creates a new standing order.
  Future<StandingOrderModel> create(Map<String, dynamic> data) async {
    final response =
        await _dio.post(ApiEndpoints.standingOrders, data: data);
    return StandingOrderModel.fromJson(
        response.data as Map<String, dynamic>);
  }

  /// Updates an existing standing order.
  Future<StandingOrderModel> update(
      String id, Map<String, dynamic> updates) async {
    final response = await _dio.patch(
      '${ApiEndpoints.standingOrders}/$id',
      data: updates,
    );
    return StandingOrderModel.fromJson(
        response.data as Map<String, dynamic>);
  }

  /// Deletes a standing order by ID.
  Future<void> delete(String id) async {
    await _dio.delete('${ApiEndpoints.standingOrders}/$id');
  }

  /// Toggles the active state of a standing order.
  Future<StandingOrderModel> toggleActive(String id, bool isActive) async {
    final response = await _dio.patch(
      '${ApiEndpoints.standingOrders}/$id',
      data: {'isActive': isActive},
    );
    return StandingOrderModel.fromJson(
        response.data as Map<String, dynamic>);
  }
}
