using CashLineERP.Application.Documents;
using CashLineERP.Contracts.Documents;
using CashLineERP.Contracts.IslamicFinance;

namespace CashLineERP.Application.IslamicFinance.Murabaha;

public sealed class IslamicFinanceMurabahaContractService : IIslamicFinanceMurabahaContractService
{
    private readonly IIslamicFinanceMurabahaContractRepository _repository;

    public IslamicFinanceMurabahaContractService(IIslamicFinanceMurabahaContractRepository repository)
    {
        _repository = repository;
    }

    public IReadOnlyCollection<DocumentAttachmentResponse> GetContracts(long murabahaCaseId) =>
        _repository.GetContracts(murabahaCaseId).Select(Map).ToArray();

    public DocumentAttachmentResponse? GetContract(long murabahaCaseId, long documentLinkId)
    {
        var entry = _repository.GetContract(murabahaCaseId, documentLinkId);
        return entry is null ? null : Map(entry);
    }

    public DocumentAttachmentResponse GenerateContract(long murabahaCaseId, long actorUserId, GenerateIslamicFinanceMurabahaContractRequest request) =>
        Map(_repository.GenerateContract(
            murabahaCaseId,
            actorUserId,
            new GenerateIslamicFinanceMurabahaContractCommand(request.ReasonText)));

    private static DocumentAttachmentResponse Map(DocumentAttachmentDetailView document) =>
        new(
            document.DocumentLinkId,
            document.ModuleCode,
            document.EntityName,
            document.EntityId,
            document.DocumentType,
            document.AttachmentCategoryCode,
            document.FileName,
            document.StorageReference,
            document.StorageProviderCode,
            document.ContentType,
            document.FileSizeBytes,
            document.ChecksumText,
            document.LifecycleStatusCode,
            document.VersionNumber,
            document.SupersededByDocumentLinkId,
            document.RetentionUntilUtc,
            document.ArchivedAtUtc,
            document.ArchivedByUserId,
            document.LifecycleNotesText,
            document.UploadedAtUtc,
            document.UploadedByUserId);
}
