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

namespace CashLineERP.Application.IslamicFinance.Murabaha;

public sealed class IslamicFinanceMurabahaAssetEvidenceService : IIslamicFinanceMurabahaAssetEvidenceService
{
    private readonly IIslamicFinanceMurabahaAssetEvidenceRepository _repository;

    public IslamicFinanceMurabahaAssetEvidenceService(IIslamicFinanceMurabahaAssetEvidenceRepository repository)
    {
        _repository = repository;
    }

    public IReadOnlyCollection<DocumentAttachmentResponse> GetEvidence(long murabahaAssetId, string? attachmentCategoryCode = null) =>
        _repository.GetEvidence(murabahaAssetId, attachmentCategoryCode).Select(Map).ToArray();

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

    public DocumentAttachmentResponse AttachEvidence(long murabahaAssetId, long actorUserId, AttachIslamicFinanceMurabahaAssetEvidenceRequest request) =>
        Map(_repository.CreateEvidence(murabahaAssetId, actorUserId, new AttachIslamicFinanceMurabahaAssetEvidenceCommand(
            request.DocumentType,
            request.AttachmentCategoryCode,
            request.FileName,
            request.StorageReference,
            request.StorageProviderCode,
            request.ContentType,
            request.FileSizeBytes,
            request.ChecksumText,
            request.RetentionUntilUtc)));

    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);
}
