/// Payment Remote Data Source
///
/// Handles API calls for payment-related data.
library;

import 'package:worker/core/constants/api_constants.dart';
import 'package:worker/core/network/dio_client.dart';
import 'package:worker/features/orders/data/models/payment_model.dart';

/// Payment Remote Data Source
class PaymentRemoteDataSource {
  const PaymentRemoteDataSource(this._dioClient);

  final DioClient _dioClient;

  /// Get payments list
  ///
  /// Calls: POST /api/method/building_material.building_material.api.payment.get_list
  /// Returns: List of payments
  Future<List<PaymentModel>> getPaymentsList({
    int limitStart = 0,
    int limitPageLength = 0,
  }) async {
    try {
      final response = await _dioClient.post<Map<String, dynamic>>(
        '${ApiConstants.frappeApiMethod}${ApiConstants.getPaymentList}',
        data: {
          'limit_start': limitStart,
          'limit_page_length': limitPageLength,
        },
      );

      final data = response.data;
      if (data == null) {
        throw Exception('No data received from getPaymentsList API');
      }

      // API returns: { "message": [...] }
      final message = data['message'];
      if (message == null) {
        throw Exception('No message field in getPaymentsList response');
      }

      final List<dynamic> paymentsList = message as List<dynamic>;
      return paymentsList
          .map((json) => PaymentModel.fromJson(json as Map<String, dynamic>))
          .toList();
    } catch (e) {
      throw Exception('Failed to get payments list: $e');
    }
  }

  /// Get payment detail
  ///
  /// Calls: POST /api/method/building_material.building_material.api.payment.get_detail
  /// Returns: Payment detail
  Future<PaymentModel> getPaymentDetail(String name) async {
    try {
      final response = await _dioClient.post<Map<String, dynamic>>(
        '${ApiConstants.frappeApiMethod}${ApiConstants.getPaymentDetail}',
        data: {'name': name},
      );

      final data = response.data;
      if (data == null) {
        throw Exception('No data received from getPaymentDetail API');
      }

      // API returns: { "message": {...} }
      final message = data['message'];
      if (message == null) {
        throw Exception('No message field in getPaymentDetail response');
      }

      return PaymentModel.fromJson(message as Map<String, dynamic>);
    } catch (e) {
      throw Exception('Failed to get payment detail: $e');
    }
  }
}
