Imports Newtonsoft.Json

Public Class cRelayHub

    Public Class cRelayHubDocument
        Public Property type As String
        Public Property base64String As String
        Public Property filename As String
        Public Property fileType As String
    End Class

    Public Class cRelayHubTransaction
        Public Property ioPartner As String
        Public Property ioDivision3 As String
        Public Property ioReference As String
    End Class

    Public Class cRelayHubObjectIdentification
        Public Property objectName As String
        Public Property objectAlias As String
        Public Property declarationType As String
        Public Property referenceNumberOverlay As String ' <--- NEU
        Public Property username As String ' <--- NEU

    End Class

    Public Class cRelayHubDv1CostAllocation
        Public Property costType As String
        Public Property costs As Decimal
        Public Property currencyCode As String
    End Class

    Public Class cRelayHubAgentContact
        Public Property contactPersonName As String
        Public Property contactPersonPhoneNumber As String
        Public Property contactPersonPosition As String
        Public Property contactPersonEmail As String ' <--- NEU
    End Class

    Public Class cRelayHubCost
        Public Property costAmount As String
        Public Property costCurrency As String
    End Class

    Public Class cRelayHubHeaderData
        Public Property agentContact As cRelayHubAgentContact
        Public Property declarantIsConsignee As Boolean
        Public Property representationRelationshipCode As String
        Public Property inputTaxDeduction As String
        Public Property procedureCodeRequested As String
        Public Property goodsStatus As String
        Public Property costs As List(Of cRelayHubCost)
        Public Property transportMeansArrivalIdentity As String
        Public Property transportMeansNationalityCode As String
        Public Property previousAdministrativeReferenceType As String
        Public Property previousAdministrativeReferenceNumber As String
        Public Property destinationFederalState As String
        Public Property destinationCountry As String
        Public Property departureCountry As String
        Public Property addressedCustomsOffice As String
        Public Property dv1CostAllocation As cRelayHubDv1CostAllocation ' <--- NEU
    End Class

    Public Class cRelayHubAddress
        Public Property addressType As String
        Public Property participantEORI As String
        Public Property participantSubsidiaryNumber As String
        Public Property companyName As String
        Public Property streetAndNumber As String
        Public Property countryCode As String
        Public Property postalCode As String
        Public Property city As String
    End Class

    Public Class cRelayHubDeclaration
        Public Property objectIdentification As cRelayHubObjectIdentification
        Public Property headerData As cRelayHubHeaderData
        Public Property addresses As List(Of cRelayHubAddress)
    End Class

    Public Class cRelayHubAdditionalData
        Public Property transaction As cRelayHubTransaction
        Public Property declaration As List(Of cRelayHubDeclaration)
    End Class

    Public Class cRelayHubJobOrderRequest
        Public Property referenceNo As String
        Public Property dispatchCountry As String
        Public Property destinationCountry As String
        Public Property regimeType As String
        Public Property customer As String
        Public Property documents As List(Of cRelayHubDocument)
        Public Property additionalData As cRelayHubAdditionalData
    End Class

    Public Class cRelayHubJobOrderResponse
        Public Property id As String
        Public Property status As String
        Public Property createdAt As String
        Public Property referenceNo As String
    End Class

    Public Class cRelayHubApiResult
        Public Property Success As Boolean
        Public Property StatusCode As Integer
        Public Property Message As String ' Zusammenfassung
        Public Property Details As String ' Volltext/Fehlermeldung
        Public Property Data As cRelayHubJobOrderResponse ' Nur bei 201
    End Class

    Public Class cRelayHub_sendToRelayHub_JobOrderRequest

        'Shared API_KEY = "2a6fe6bf-6547-4d56-b14a-8a18f94f9e94"
        'Shared API_URL = "dev-relayhub.singlewindow.io/api"
        Shared API_URL = "https://dev-relayhub.singlewindow.io/api/v1-0"

        Public Shared Function query_declarations(request As cRelayHubJobOrderRequest) As cRelayHubApiResult
            Dim result As New cRelayHubApiResult()
            Try
                ' This example assumes the Chilkat API to have been previously unlocked.
                ' See Global Unlock Sample for sample code.
                VERAG_PROG_ALLGEMEIN.cChilkat_Helper.UnlockCilkat()

                Dim success As Boolean


                ' HTTP-Client initialisieren
                Dim http As New Chilkat.Http
                ' JSON vorbereiten

                ' Request-Objekt in JSON-String umwandeln
                Dim jsonPayload As String = JsonConvert.SerializeObject(request)
                '   MsgBox(jsonPayload)


                ' Größe in Bytes
                Dim payloadSizeBytes As Integer = System.Text.Encoding.UTF8.GetByteCount(jsonPayload)

                ' Größe in Kilobytes (1 KB = 1024 Bytes)
                Dim payloadSizeKb As Double = payloadSizeBytes / 1024.0

                Console.WriteLine("📦 Größe des JSON-Payload:")
                Console.WriteLine(payloadSizeBytes & " Bytes (" & Math.Round(payloadSizeKb, 2) & " KB)")

                ' Anfrage senden
                Dim response As Chilkat.HttpResponse = http.PostJson2(API_URL & "/job-orders/init", "application/json", jsonPayload)
                MsgBox(jsonPayload)

                Console.WriteLine(jsonPayload)
                If http.LastMethodSuccess <> True Then
                    result.Success = False
                    result.StatusCode = 0
                    result.Message = "Verbindungsfehler"
                    result.Details = http.LastErrorText
                    Return result
                End If

                result.StatusCode = response.StatusCode

                Select Case response.StatusCode
                    Case 201
                        Try
                            Dim jobResponse As cRelayHubJobOrderResponse = JsonConvert.DeserializeObject(Of cRelayHubJobOrderResponse)(response.BodyStr)
                            result.Success = True
                            result.Message = "Job Order erfolgreich erstellt"
                            result.Data = jobResponse
                            result.Details = $"ID: {jobResponse.id}, Referenz: {jobResponse.referenceNo}"
                        Catch ex As Exception
                            result.Success = False
                            result.StatusCode = 999
                            result.Message = "Antwort konnte nicht gelesen werden"
                            result.Details = ex.Message
                        End Try

                    Case 400 To 499
                        result.Success = False
                        result.Message = "Client-Fehler"
                        result.Message = "StatusCode: " & response.StatusCode
                        result.Details = "StatusLine: " & response.StatusLine
                        result.Details = "StatusText: " & response.StatusText
                        result.Details = "BodyStr: " & response.BodyStr

                    Case 500 To 599
                        result.Success = False
                        result.Message = "Server-Fehler"
                        result.Message = "StatusCode: " & response.StatusCode
                        result.Details = "StatusLine: " & response.StatusLine
                        result.Details = "StatusText: " & response.StatusText
                        result.Details = "BodyStr: " & response.BodyStr

                    Case Else
                        result.Success = False
                        result.Message = $"Unbekannter Fehler (Status {response.StatusCode})"
                        result.Details = response.BodyStr
                End Select

                Console.WriteLine(result.Message)
                Console.WriteLine(result.Details)

                Return result


            Catch ex As Exception
                VERAG_PROG_ALLGEMEIN.cErrorHandler.ERR(ex.Message, ex.StackTrace, System.Reflection.MethodInfo.GetCurrentMethod.Name)

            End Try
            Return Nothing
        End Function

        Function CreateSampleJobOrderRequest() As cRelayHubJobOrderRequest
            Dim request As New cRelayHubJobOrderRequest With {
                .referenceNo = "1001K",
                .dispatchCountry = "TR",
                .destinationCountry = "EN",
                .regimeType = "IM",
                .customer = "AVISO",
                .documents = New List(Of cRelayHubDocument) From {
                    New cRelayHubDocument With {.type = "base64", .base64String = "SGVsbG8sIHRoaXMgaXMgYSBzYW1wbGUgYmFzZTY0IHN0cmluZy4=", .filename = "test.txt", .fileType = "invoice"},
                    New cRelayHubDocument With {.type = "base64", .base64String = "SGVsbG8sIHRoaXMgaXMgYSBzYW1wbGUgYmFzZTY0IHN0cmluZy4=", .filename = "test2.txt", .fileType = "atr"},
                    New cRelayHubDocument With {.type = "base64", .base64String = "SGVsbG8sIHRoaXMgaXMgYSBzYW1wbGUgYmFzZTY0IHN0cmluZy4=", .filename = "test3.txt", .fileType = "cmr"}
                },
                .additionalData = New cRelayHubAdditionalData With {
                    .transaction = New cRelayHubTransaction With {
                        .ioPartner = "VERA",
                        .ioDivision3 = "SUB",
                        .ioReference = "4803/25001763_1301250935SS/samimx"
                    },
                    .declaration = New List(Of cRelayHubDeclaration) From {
                        New cRelayHubDeclaration With {
                            .objectIdentification = New cRelayHubObjectIdentification With {
                                .objectName = "4803/25001763",
                                .objectAlias = "1349846",
                                .declarationType = "EZA-D"
                            },
                            .headerData = New cRelayHubHeaderData With {
                                .agentContact = New cRelayHubAgentContact With {
                                    .contactPersonName = "AMANN",
                                    .contactPersonPhoneNumber = "+49 123 456 789",
                                    .contactPersonPosition = "Manager"
                                },
                                .declarantIsConsignee = True,
                                .representationRelationshipCode = "1",
                                .inputTaxDeduction = "true",
                                .procedureCodeRequested = "42",
                                .goodsStatus = "EU",
                                .costs = New List(Of cRelayHubCost) From {
                                    New cRelayHubCost With {.costAmount = "25909.92", .costCurrency = "EUR"}
                                },
                                .transportMeansArrivalIdentity = "PB1552EC",
                                .transportMeansNationalityCode = "BG",
                                .previousAdministrativeReferenceType = "T1",
                                .previousAdministrativeReferenceNumber = "25TR160100001472M0",
                                .destinationFederalState = "07",
                                .destinationCountry = "DE",
                                .departureCountry = "TR"
                            },
                            .addresses = New List(Of cRelayHubAddress) From {
                                New cRelayHubAddress With {.addressType = "CZ", .participantEORI = "EORI12345", .participantSubsidiaryNumber = "001", .companyName = "SISECAM DIS TIC.A.S.", .streetAndNumber = "D-100 KARAYOLU CD.YAYLA MH.NO.70/C", .countryCode = "TR", .postalCode = "34949", .city = "TUZLA ISTANBUL"},
                                New cRelayHubAddress With {.addressType = "CN", .participantEORI = "EORI67890", .participantSubsidiaryNumber = "002", .companyName = "POLYNT COMPOSITES GERMANY GMBH", .streetAndNumber = "KIESELSTRASSE 2", .countryCode = "DE", .postalCode = "56357", .city = "MIEHLEN"}
                            }
                        }
                    }
                }
            }

            Return request
        End Function

    End Class
End Class
