using CashLineERP.Contracts.IslamicFinance;

namespace CashLineERP.Application.IslamicFinance.Murabaha;

public sealed class IslamicFinanceMurabahaAccountingHookService : IIslamicFinanceMurabahaAccountingHookService
{
    private readonly IIslamicFinanceMurabahaAccountingHookRepository _repository;

    public IslamicFinanceMurabahaAccountingHookService(IIslamicFinanceMurabahaAccountingHookRepository repository)
    {
        _repository = repository;
    }

    public IReadOnlyCollection<IslamicFinanceAccountingHookResponse> GetHooks(long murabahaCaseId, string? postingStatusCode = null) =>
        _repository.GetHooks(murabahaCaseId, postingStatusCode).Select(Map).ToArray();

    public IslamicFinanceAccountingHookResponse? GetHook(long murabahaCaseId, long accountingHookId)
    {
        var entry = _repository.GetHook(murabahaCaseId, accountingHookId);
        return entry is null ? null : Map(entry);
    }

    public IslamicFinanceAccountingHookResponse RegisterHook(long murabahaCaseId, long actorUserId) =>
        Map(_repository.RegisterHook(murabahaCaseId, actorUserId));

    public IslamicFinanceAccountingHookResponse PublishHook(long murabahaCaseId, long accountingHookId, long actorUserId) =>
        Map(_repository.PublishHook(murabahaCaseId, accountingHookId, actorUserId));

    private static IslamicFinanceAccountingHookResponse Map(IslamicFinanceAccountingHookDetailView entry) =>
        new()
        {
            Id = entry.AccountingHookId,
            SourceEntityType = entry.SourceEntityType,
            SourceEntityId = entry.SourceEntityId,
            FundingSourceMode = entry.FundingSourceMode,
            ProductType = entry.ProductType,
            CustomerPartyId = entry.CustomerPartyId,
            PartnerLenderId = entry.PartnerLenderId,
            GeneralLedgerBatchId = entry.GeneralLedgerBatchId,
            PostingStatusCode = entry.PostingStatusCode,
            CreatedAtUtc = entry.CreatedAtUtc,
            CreatedByUserId = entry.CreatedByUserId,
            UpdatedAtUtc = entry.UpdatedAtUtc,
            UpdatedByUserId = entry.UpdatedByUserId
        };
}
