using CashLineERP.Contracts.IslamicFinance;

namespace CashLineERP.Application.IslamicFinance.ContractTemplates;

public sealed class IslamicFinanceContractTemplateService : IIslamicFinanceContractTemplateService
{
    private readonly IIslamicFinanceContractTemplateRepository _repository;

    public IslamicFinanceContractTemplateService(IIslamicFinanceContractTemplateRepository repository)
    {
        _repository = repository;
    }

    public IReadOnlyCollection<IslamicFinanceContractTemplateResponse> GetContractTemplates(
        bool activeOnly = false,
        long? productProfileId = null,
        string? languageCode = null) =>
        _repository.GetContractTemplates(activeOnly, productProfileId, languageCode).Select(Map).ToArray();

    public IslamicFinanceContractTemplateResponse? GetContractTemplate(long contractTemplateId)
    {
        var entry = _repository.GetContractTemplate(contractTemplateId);
        return entry is null ? null : Map(entry);
    }

    public IslamicFinanceContractTemplateResponse CreateContractTemplate(CreateIslamicFinanceContractTemplateRequest request) =>
        Map(_repository.Create(new CreateIslamicFinanceContractTemplateCommand(
            request.ProductProfileId,
            request.TemplateCode,
            request.TemplateName,
            request.LanguageCode)));

    public IslamicFinanceContractTemplateResponse SubmitContractTemplate(long contractTemplateId, long actorUserId) =>
        Map(_repository.Submit(contractTemplateId, actorUserId));

    public IslamicFinanceContractTemplateResponse ApproveContractTemplate(long contractTemplateId, long actorUserId) =>
        Map(_repository.Approve(contractTemplateId, actorUserId));

    public IslamicFinanceContractTemplateResponse ActivateContractTemplate(long contractTemplateId, long actorUserId) =>
        Map(_repository.Activate(contractTemplateId, actorUserId));

    private static IslamicFinanceContractTemplateResponse Map(IslamicFinanceContractTemplateDetailView entry) =>
        new()
        {
            Id = entry.ContractTemplateId,
            ProductProfileId = entry.ProductProfileId,
            TemplateCode = entry.TemplateCode,
            TemplateName = entry.TemplateName,
            LanguageCode = entry.LanguageCode,
            StatusCode = entry.StatusCode,
            IsActive = entry.IsActive,
            SubmittedAtUtc = entry.SubmittedAtUtc,
            SubmittedByUserId = entry.SubmittedByUserId,
            ApprovedAtUtc = entry.ApprovedAtUtc,
            ApprovedByUserId = entry.ApprovedByUserId,
            ActivatedAtUtc = entry.ActivatedAtUtc,
            ActivatedByUserId = entry.ActivatedByUserId
        };
}
