/// Repository Implementation: Price Policy Repository
///
/// Concrete implementation of the PricePolicyRepository interface.
/// Fetches price policy documents from remote API.
library;

import 'package:worker/features/price_policy/data/datasources/price_policy_remote_datasource.dart';
import 'package:worker/features/price_policy/domain/entities/price_document.dart';
import 'package:worker/features/price_policy/domain/repositories/price_policy_repository.dart';

/// Price Policy Repository Implementation
class PricePolicyRepositoryImpl implements PricePolicyRepository {
  /// Remote data source
  final PricePolicyRemoteDataSource remoteDataSource;

  /// Constructor
  const PricePolicyRepositoryImpl({
    required this.remoteDataSource,
  });

  @override
  Future<List<PriceDocument>> getAllDocuments() async {
    try {
      // Fetch documents separately to maintain category info
      final pricingRuleModels =
          await remoteDataSource.getDocumentsByType('PRICING_RULE');
      final priceListModels =
          await remoteDataSource.getDocumentsByType('PRICE_LIST');

      final entities = <PriceDocument>[
        ...pricingRuleModels.map((model) => model.toEntity(DocumentCategory.policy)),
        ...priceListModels.map((model) => model.toEntity(DocumentCategory.priceList)),
      ];

      // Sort by update date (newest first)
      entities.sort((a, b) => b.updatedAt.compareTo(a.updatedAt));

      return entities;
    } catch (e) {
      // In production, this should throw proper domain failures
      rethrow;
    }
  }

  @override
  Future<List<PriceDocument>> getDocumentsByCategory(
    DocumentCategory category,
  ) async {
    try {
      // Convert category to API parameter
      final pricingType = category.apiValue;

      // Fetch documents by type from API
      final models = await remoteDataSource.getDocumentsByType(pricingType);

      // Convert models to entities with the correct category
      final entities = models.map((model) => model.toEntity(category)).toList();

      // Sort by update date (newest first)
      entities.sort((a, b) => b.updatedAt.compareTo(a.updatedAt));

      return entities;
    } catch (e) {
      rethrow;
    }
  }

  @override
  Future<PriceDocument?> getDocumentById(String documentId) async {
    try {
      // Since API doesn't have a get-by-id endpoint,
      // we fetch all and find the matching one
      final allDocuments = await getAllDocuments();
      return allDocuments.firstWhere(
        (doc) => doc.title == documentId,
        orElse: () => throw Exception('Document not found'),
      );
    } catch (e) {
      return null;
    }
  }

  @override
  Future<List<PriceDocument>> refreshDocuments() async {
    try {
      // Refresh is same as getAllDocuments since we're fetching from API
      return await getAllDocuments();
    } catch (e) {
      rethrow;
    }
  }
}
