using CashLineERP.Contracts.IslamicFinance;

namespace CashLineERP.Application.IslamicFinance.Facilities;

public sealed class IslamicFinanceFacilityService : IIslamicFinanceFacilityService
{
    private readonly IIslamicFinanceFacilityRepository _repository;

    public IslamicFinanceFacilityService(IIslamicFinanceFacilityRepository repository)
    {
        _repository = repository;
    }

    public IReadOnlyCollection<IslamicFinanceFacilityResponse> GetFacilities(
        bool activeOnly = false,
        long? customerPartyId = null,
        long? partnerLenderId = null) =>
        _repository.GetFacilities(activeOnly, customerPartyId, partnerLenderId).Select(Map).ToArray();

    public IslamicFinanceFacilityResponse? GetFacility(long facilityId)
    {
        var entry = _repository.GetFacility(facilityId);
        return entry is null ? null : Map(entry);
    }

    public IslamicFinanceFacilityResponse CreateFacility(CreateIslamicFinanceFacilityRequest request) =>
        Map(_repository.Create(new CreateIslamicFinanceFacilityCommand(
            request.PartnerLenderId,
            request.CustomerPartyId,
            request.ProductProfileId,
            request.FacilityNumber,
            request.CurrencyCode,
            request.ApprovedLimitAmount,
            request.UtilizedAmount)));

    public IslamicFinanceFacilityResponse SubmitFacility(long facilityId, long actorUserId) =>
        Map(_repository.Submit(facilityId, actorUserId));

    public IslamicFinanceFacilityResponse ApproveFacility(long facilityId, long actorUserId) =>
        Map(_repository.Approve(facilityId, actorUserId));

    public IslamicFinanceFacilityResponse ActivateFacility(long facilityId, long actorUserId) =>
        Map(_repository.Activate(facilityId, actorUserId));

    private static IslamicFinanceFacilityResponse Map(IslamicFinanceFacilityDetailView entry) =>
        new()
        {
            Id = entry.FacilityId,
            PartnerLenderId = entry.PartnerLenderId,
            CustomerPartyId = entry.CustomerPartyId,
            ProductProfileId = entry.ProductProfileId,
            FacilityNumber = entry.FacilityNumber,
            CurrencyCode = entry.CurrencyCode,
            ApprovedLimitAmount = entry.ApprovedLimitAmount,
            UtilizedAmount = entry.UtilizedAmount,
            AvailableAmount = entry.AvailableAmount,
            StatusCode = entry.StatusCode,
            IsActive = entry.IsActive,
            SubmittedAtUtc = entry.SubmittedAtUtc,
            SubmittedByUserId = entry.SubmittedByUserId,
            ApprovedAtUtc = entry.ApprovedAtUtc,
            ApprovedByUserId = entry.ApprovedByUserId,
            ActivatedAtUtc = entry.ActivatedAtUtc,
            ActivatedByUserId = entry.ActivatedByUserId
        };
}
