using CashLineERP.Contracts.IslamicFinance;

namespace CashLineERP.Application.IslamicFinance.PartnerLenders;

public sealed class IslamicFinancePartnerService : IIslamicFinancePartnerService
{
    private readonly IIslamicFinancePartnerRepository _repository;

    public IslamicFinancePartnerService(IIslamicFinancePartnerRepository repository)
    {
        _repository = repository;
    }

    public IReadOnlyCollection<IslamicFinancePartnerLenderResponse> GetPartnerLenders(bool activeOnly = false) =>
        _repository.GetPartnerLenders(activeOnly).Select(Map).ToArray();

    public IslamicFinancePartnerLenderResponse? GetPartnerLender(long partnerLenderId)
    {
        var entry = _repository.GetPartnerLender(partnerLenderId);
        return entry is null ? null : Map(entry);
    }

    public IslamicFinancePartnerLenderResponse CreatePartnerLender(CreateIslamicFinancePartnerLenderRequest request) =>
        Map(_repository.Create(new CreateIslamicFinancePartnerLenderCommand(
            request.PartnerLenderPartyId,
            request.DefaultCurrencyCode,
            request.SupportsMurabaha,
            request.SupportsReceivablesFinance,
            request.SupportsTawarruq)));

    public IslamicFinancePartnerLenderResponse SubmitPartnerLender(long partnerLenderId, long actorUserId) =>
        Map(_repository.Submit(partnerLenderId, actorUserId));

    public IslamicFinancePartnerLenderResponse ApprovePartnerLender(long partnerLenderId, long actorUserId) =>
        Map(_repository.Approve(partnerLenderId, actorUserId));

    public IslamicFinancePartnerLenderResponse ActivatePartnerLender(long partnerLenderId, long actorUserId) =>
        Map(_repository.Activate(partnerLenderId, actorUserId));

    private static IslamicFinancePartnerLenderResponse Map(IslamicFinancePartnerLenderDetailView entry) =>
        new()
        {
            Id = entry.PartnerLenderId,
            PartnerLenderPartyId = entry.PartnerLenderPartyId,
            StatusCode = entry.StatusCode,
            DefaultCurrencyCode = entry.DefaultCurrencyCode,
            SupportsMurabaha = entry.SupportsMurabaha,
            SupportsReceivablesFinance = entry.SupportsReceivablesFinance,
            SupportsTawarruq = entry.SupportsTawarruq,
            IsActive = entry.IsActive,
            SubmittedAtUtc = entry.SubmittedAtUtc,
            SubmittedByUserId = entry.SubmittedByUserId,
            ApprovedAtUtc = entry.ApprovedAtUtc,
            ApprovedByUserId = entry.ApprovedByUserId,
            ActivatedAtUtc = entry.ActivatedAtUtc,
            ActivatedByUserId = entry.ActivatedByUserId
        };
}
