' =============================================
' Track it All API Client
' Purpose: Upload outlet sync Excel file to Track it All API
'          POST multipart/form-data with X-API-KEY header
' =============================================

Imports System.IO
Imports System.Net.Http
Imports System.Net.Http.Headers
Imports System.Text
Imports Superbowl_Daily_2.ProjectFunctions
Imports Superbowl_Daily_2.SystemFunctions

Public Class TrackItAllAPIClient

    Private ReadOnly baseUrl As String
    Private ReadOnly apiKey As String
    Private ReadOnly httpClient As HttpClient
    Private ReadOnly processName As String

    ' =============================================
    ' Constructor
    ' =============================================
    Public Sub New(Optional processName As String = "Track it All API")
        Me.baseUrl = My.Settings.TrackItAllAPIBaseUrl.TrimEnd("/"c)
        Me.apiKey = My.Settings.TrackItAllAPIKey
        Me.processName = processName

        Me.httpClient = New HttpClient()
        Me.httpClient.Timeout = TimeSpan.FromSeconds(120)
        Me.httpClient.DefaultRequestHeaders.Add("X-API-KEY", apiKey)
    End Sub

    ' =============================================
    ' Upload Outlets File - multipart/form-data POST
    ' =============================================
    Public Function UploadOutletsFile(filePath As String, mode As String) As TrackItAllUploadResult
        Dim result As New TrackItAllUploadResult()

        Try
            If Not File.Exists(filePath) Then
                result.Success = False
                result.ErrorMessage = "File not found: " & filePath
                WriteLog("error", processName, "Upload Outlets", result.ErrorMessage)
                Return result
            End If

            Dim url As String = baseUrl & "/rgbc/updateOutlets"
            WriteLog("info", processName, "Upload Outlets", "Posting to: " & url & " | mode=" & mode)

            Using content As New MultipartFormDataContent()
                Dim fileBytes As Byte() = File.ReadAllBytes(filePath)
                Dim fileContent As New ByteArrayContent(fileBytes)
                fileContent.Headers.ContentType = New MediaTypeHeaderValue("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")
                content.Add(fileContent, "file", Path.GetFileName(filePath))
                content.Add(New StringContent(mode), "mode")

                Dim response As HttpResponseMessage = httpClient.PostAsync(url, content).Result
                Dim responseBody As String = response.Content.ReadAsStringAsync().Result

                If response.IsSuccessStatusCode Then
                    result.Success = True
                    result.ResponseBody = responseBody
                    WriteLog("info", processName, "Upload Outlets", "Success: " & response.StatusCode.ToString())
                Else
                    result.Success = False
                    result.ErrorMessage = "HTTP " & response.StatusCode.ToString() & ": " & responseBody
                    result.ResponseBody = responseBody
                    WriteLog("error", processName, "Upload Outlets", result.ErrorMessage)
                End If
            End Using

        Catch ex As Exception
            result.Success = False
            result.ErrorMessage = ex.Message
            If ex.InnerException IsNot Nothing Then
                result.ErrorMessage &= " | " & ex.InnerException.Message
            End If
            WriteLog("error", processName, "Upload Outlets Exception", ex.Message & " :: " & ex.StackTrace)
        End Try

        Return result
    End Function

    ' =============================================
    ' Dispose
    ' =============================================
    Public Sub Dispose()
        If httpClient IsNot Nothing Then
            httpClient.Dispose()
        End If
    End Sub

End Class

' =============================================
' Upload result type
' =============================================
Public Class TrackItAllUploadResult
    Public Property Success As Boolean
    Public Property ErrorMessage As String
    Public Property ResponseBody As String
End Class
