using CashLineERP.Contracts.IslamicFinance;
using CashLineERP.SharedKernel.IslamicFinance;

namespace CashLineERP.Application.IslamicFinance.ProductProfiles;

public sealed class IslamicFinanceProductService : IIslamicFinanceProductService
{
    private readonly IIslamicFinanceProductRepository _repository;

    public IslamicFinanceProductService(IIslamicFinanceProductRepository repository)
    {
        _repository = repository;
    }

    public IReadOnlyCollection<IslamicFinanceProductProfileResponse> GetProductProfiles(bool activeOnly = false, string? productType = null) =>
        _repository.GetProductProfiles(activeOnly, productType).Select(Map).ToArray();

    public IslamicFinanceProductProfileResponse? GetProductProfile(long productProfileId)
    {
        var entry = _repository.GetProductProfile(productProfileId);
        return entry is null ? null : Map(entry);
    }

    public IslamicFinanceProductProfileResponse CreateProductProfile(CreateIslamicFinanceProductProfileRequest request) =>
        Map(_repository.Create(new CreateIslamicFinanceProductProfileCommand(
            request.ProductType,
            request.ProductCode,
            request.ProductName,
            request.RequiresShariahReview,
            request.AllowsPartnerFunding,
            request.AllowsCashLineFunding)));

    public IslamicFinanceProductProfileResponse SubmitProductProfile(long productProfileId, long actorUserId) =>
        Map(_repository.Submit(productProfileId, actorUserId));

    public IslamicFinanceProductProfileResponse ApproveProductProfile(long productProfileId, long actorUserId) =>
        Map(_repository.Approve(productProfileId, actorUserId));

    public IslamicFinanceProductProfileResponse ActivateProductProfile(long productProfileId, long actorUserId) =>
        Map(_repository.Activate(productProfileId, actorUserId));

    private static IslamicFinanceProductProfileResponse Map(IslamicFinanceProductProfileDetailView entry) =>
        new()
        {
            Id = entry.ProductProfileId,
            ProductType = IslamicFinanceProductCatalog.NormalizeProductType(entry.ProductType),
            ProductCode = entry.ProductCode,
            ProductName = entry.ProductName,
            StatusCode = entry.StatusCode,
            IsActive = entry.IsActive,
            RequiresShariahReview = entry.RequiresShariahReview,
            AllowsPartnerFunding = entry.AllowsPartnerFunding,
            AllowsCashLineFunding = entry.AllowsCashLineFunding,
            SubmittedAtUtc = entry.SubmittedAtUtc,
            SubmittedByUserId = entry.SubmittedByUserId,
            ApprovedAtUtc = entry.ApprovedAtUtc,
            ApprovedByUserId = entry.ApprovedByUserId,
            ActivatedAtUtc = entry.ActivatedAtUtc,
            ActivatedByUserId = entry.ActivatedByUserId
        };
}
