
Imports System.IO
Imports System.Net
Imports System.Security.Cryptography
Imports System.Text
Imports Newtonsoft.Json

Public Class cBZST_UID_REST

    Shared ReadOnly ApiHost As String = "api.evatr.vies.bzst.de"
    Shared ReadOnly ApiPort As Integer = 443
    Shared ReadOnly ApiBasePath As String = "/v1"

    ' === 1. MAC Authentication Header Builder ===
    Shared Function BuildMacHeader(httpMethod As String, path As String, body As String, id As String, base64Key As String) As String
        Dim ts As String = CLng((DateTime.UtcNow - #1/1/1970#).TotalSeconds).ToString()
        Dim nonce As String = Guid.NewGuid().ToString("N").Substring(0, 12)

        Dim bodyHashPart As String = ""
        If httpMethod = "POST" AndAlso body IsNot Nothing Then
            Using sha = SHA256.Create()
                bodyHashPart = Convert.ToBase64String(sha.ComputeHash(Encoding.UTF8.GetBytes(body)))
            End Using
        End If

        Dim macInput As String = $"{ts}{vbLf}{nonce}{vbLf}{httpMethod}{vbLf}{path}{vbLf}{ApiHost}{vbLf}{ApiPort}{vbLf}{bodyHashPart}{vbLf}"
        Dim keyBytes As Byte() = Convert.FromBase64String(base64Key)
        Dim hmac As New HMACSHA256(keyBytes)
        Dim macSig As String = Convert.ToBase64String(hmac.ComputeHash(Encoding.UTF8.GetBytes(macInput)))

        Return $"MAC id=""{id}"", ts=""{ts}"", nonce=""{nonce}"", mac=""{macSig}"""
    End Function

    ' === 2. HTTP Call Helper ===
    Shared Function DoRequest(httpMethod As String, path As String, body As String, authHeader As String) As String
        Dim url As String = $"https://{ApiHost}{path}"
        Dim req = CType(WebRequest.Create(url), HttpWebRequest)
        req.Method = httpMethod
        req.Headers.Add("Authorization", authHeader)
        If httpMethod = "POST" Then
            req.ContentType = "application/json"
            Dim bodyBytes = Encoding.UTF8.GetBytes(body)
            req.ContentLength = bodyBytes.Length
            Using s = req.GetRequestStream()
                s.Write(bodyBytes, 0, bodyBytes.Length)
            End Using
        Else
            req.Accept = "application/json"
        End If

        Using resp = CType(req.GetResponse(), HttpWebResponse)
            Using sr = New StreamReader(resp.GetResponseStream())
                Return sr.ReadToEnd()
            End Using
        End Using
    End Function

    ' === 3. CheckVat (einfach) ===
    Public Shared Function CheckVat(countryCode As String, vatNumber As String, apiId As String, apiKeyBase64 As String) As String

        Dim path = $"{ApiBasePath}/euvat/{countryCode}{vatNumber}"
        Dim auth = BuildMacHeader("GET", path, Nothing, apiId, apiKeyBase64)
        Return DoRequest("GET", path, Nothing, auth)
    End Function

    ' === 4. CheckVatQualified (mit Zusatzdaten) ===
    Public Shared Function CheckVatQualified(countryCode As String, vatNumber As String,
                                      street As String, postalCode As String, city As String,
                                      apiId As String, apiKeyBase64 As String) As String

        Dim path = $"{ApiBasePath}/euvat/qualified"
        Dim payload = New With {
            .countryCode = countryCode,
            .vatNumber = vatNumber,
            .street = street,
            .postalCode = postalCode,
            .city = city
        }
        Dim jsonBody As String = JsonConvert.SerializeObject(payload)
        Dim auth = BuildMacHeader("POST", path, jsonBody, apiId, apiKeyBase64)
        Return DoRequest("POST", path, jsonBody, auth)
    End Function

    ' === 5. Statusmeldungen abrufen ===
    Public Function GetStatusMessages(apiId As String, apiKeyBase64 As String) As String
        Dim path = $"{ApiBasePath}/info/statusmeldungen"
        Dim auth = BuildMacHeader("GET", path, Nothing, apiId, apiKeyBase64)
        Return DoRequest("GET", path, Nothing, auth)
    End Function


    Sub EXAMPLE()
        Dim apiId As String = "DEINE_ID"
        Dim apiKey As String = "DEIN_BASE64_KEY"

        ' 1) Einfache Prüfung
        Dim simple = CheckVat("AT", "U18522105", apiId, apiKey)
        Console.WriteLine("Simple VAT Response: " & simple)

        ' 2) Qualifizierte Prüfung
        Dim qual = CheckVatQualified("DE", "123456789", "Musterstr. 1", "12345", "Musterstadt", apiId, apiKey)
        Console.WriteLine("Qualified VAT Response: " & qual)

        ' 3) Statusmeldungen
        Dim status = GetStatusMessages(apiId, apiKey)
        Console.WriteLine("Status Messages: " & status)
    End Sub
End Class