/// Remote Data Source: Price Policy
///
/// Handles API communication for price policy documents.
library;

import 'package:dio/dio.dart';
import 'package:worker/core/network/dio_client.dart';
import 'package:worker/features/price_policy/data/models/price_document_model.dart';

/// Price Policy Remote Data Source Interface
abstract class PricePolicyRemoteDataSource {
  /// Get documents by pricing type
  Future<List<PriceDocumentModel>> getDocumentsByType(String pricingType);

  /// Get all documents (both pricing rule and price list)
  Future<List<PriceDocumentModel>> getAllDocuments();
}

/// Price Policy Remote Data Source Implementation
class PricePolicyRemoteDataSourceImpl implements PricePolicyRemoteDataSource {

  const PricePolicyRemoteDataSourceImpl(this._dioClient);
  final DioClient _dioClient;

  @override
  Future<List<PriceDocumentModel>> getDocumentsByType(String pricingType) async {
    try {
      final response = await _dioClient.post<Map<String, dynamic>>(
        '/api/method/building_material.building_material.api.pricing.get_pricing_info',
        data: {
          'pricing_type': pricingType,
          'limit_page_length': 0,
          'limit_start': 0,
        },
      );

      if (response.data == null) {
        return [];
      }

      final apiResponse = PricingApiResponse.fromJson(response.data!);
      return apiResponse.message;
    } on DioException catch (e) {
      throw Exception('Failed to fetch pricing documents: ${e.message}');
    } catch (e) {
      throw Exception('Failed to parse pricing documents: $e');
    }
  }

  @override
  Future<List<PriceDocumentModel>> getAllDocuments() async {
    try {
      // Fetch both pricing rule and price list in parallel
      final results = await Future.wait([
        getDocumentsByType('PRICING_RULE'),
        getDocumentsByType('PRICE_LIST'),
      ]);

      // Combine results
      return [...results[0], ...results[1]];
    } catch (e) {
      throw Exception('Failed to fetch all documents: $e');
    }
  }
}
