/// Invoice Remote Data Source
///
/// Handles API calls for invoice-related data.
library;

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

/// Invoice Remote Data Source
class InvoiceRemoteDataSource {
  const InvoiceRemoteDataSource(this._dioClient);

  final DioClient _dioClient;

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

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

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

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

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

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

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

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