Imports DigitalData.Modules.Database
Imports DigitalData.Modules.Logging

Namespace ZUGFeRD
    Public Class HistoryFunctions
        Private ReadOnly _logConfig As LogConfig
        Private ReadOnly _logger As Logger
        Private ReadOnly _mssql As MSSQLServer

        Public Sub New(LogConfig As LogConfig, MSSQL As MSSQLServer)
            _logConfig = LogConfig
            _logger = _logConfig.GetLogger()
            _mssql = MSSQL
        End Sub

        Public Function Update_HistoryEntry(pMessageId As String, pMD5Checksum As String, pMessage As String) As Boolean
            Try
                _logger.Info("Updating History Entry for MessageId [{0}] with comment [{1}]", pMessageId, pMessage)
                ' Only look for history entry by MessageId since the MD5 Hash might not be generated yet

                Using oConnection = _mssql.GetConnection()
                    ' 09.07.2021: This can't be in the transaction since the history 
                    ' Entry needs to be accessed by MoveAndRenameEmailToRejected shortly after

                    Dim oSQL = $"UPDATE TBEMLP_HISTORY SET 
                        COMMENT = '{pMessage}', 
                        MD5HASH = '{pMD5Checksum}' 
                        WHERE EMAIL_MSGID = '{pMessageId}'"

                    'If pMessage.Contains("REJECTED") Then
                    If pMessage.Contains(EmailStrings.ErrorCodePraefix) Then
                        oSQL = $"UPDATE TBEMLP_HISTORY SET 
                            COMMENT = '{pMessage}', 
                            MD5HASH = '{pMD5Checksum}', 
                            STATUS = 'REJECTED', 
                            CUST_REJECTED = 1, 
                            CUST_REJECTED_WHEN = GETDATE()
                            WHERE EMAIL_MSGID = '{pMessageId}'"
                    End If

                    _mssql.ExecuteNonQueryWithConnectionObject(oSQL, oConnection)
                End Using

                _logger.Debug("History Entry created!")

                Return True
            Catch ex As Exception
                _logger.Warn("History Entry count not be updated for message id [{0}] and md5 [{1}]", pMessageId, pMD5Checksum)
                _logger.Error(ex)

                Return False
            End Try
        End Function
    End Class
End Namespace