using CashLineERP.Contracts.IslamicFinance;

namespace CashLineERP.Application.IslamicFinance.Murabaha;

public sealed class IslamicFinanceMurabahaAssetService : IIslamicFinanceMurabahaAssetService
{
    private readonly IIslamicFinanceMurabahaAssetRepository _repository;

    public IslamicFinanceMurabahaAssetService(IIslamicFinanceMurabahaAssetRepository repository)
    {
        _repository = repository;
    }

    public IReadOnlyCollection<IslamicFinanceMurabahaAssetResponse> GetAssets(long murabahaCaseId) =>
        _repository.GetAssets(murabahaCaseId).Select(Map).ToArray();

    public IslamicFinanceMurabahaAssetResponse? GetAsset(long murabahaAssetId)
    {
        var entry = _repository.GetAsset(murabahaAssetId);
        return entry is null ? null : Map(entry);
    }

    public IslamicFinanceMurabahaAssetResponse CreateAsset(long murabahaCaseId, CreateIslamicFinanceMurabahaAssetRequest request) =>
        Map(_repository.Create(new CreateIslamicFinanceMurabahaAssetCommand(
            murabahaCaseId,
            request.AssetDescription,
            request.SupplierPartyId,
            request.PurchaseReferenceNumber,
            request.PurchaseCostAmount)));

    private static IslamicFinanceMurabahaAssetResponse Map(IslamicFinanceMurabahaAssetDetailView entry) =>
        new()
        {
            Id = entry.MurabahaAssetId,
            MurabahaCaseId = entry.MurabahaCaseId,
            AssetDescription = entry.AssetDescription,
            SupplierPartyId = entry.SupplierPartyId,
            PurchaseReferenceNumber = entry.PurchaseReferenceNumber,
            PurchaseCostAmount = entry.PurchaseCostAmount,
            CreatedAtUtc = entry.CreatedAtUtc,
            CreatedByUserId = entry.CreatedByUserId,
            UpdatedAtUtc = entry.UpdatedAtUtc,
            UpdatedByUserId = entry.UpdatedByUserId
        };
}
