<%
'=======================================================================================================================
' Orders Repository
'=======================================================================================================================
Class OrdersRepository_Class

    ' Creates a new order row for the given email/jurisdiction, generates a single-use
    ' token that expires after OrderTokenExpirationHours, and returns that token.
    Public Function CreateOrder(email, jurisdictionNumber)
        Dim token, expiresAt
        token = NewGuid()
        expiresAt = DateAdd("h", TokenExpirationHours(), Now())

        DAL.Execute _
            "INSERT INTO Orders (Email, JurisdictionNumber, Token, TokenExpiresAt, CreatedAt) VALUES (?, ?, ?, ?, ?)", _
            Array(email, jurisdictionNumber, token, expiresAt, Now())

        CreateOrder = token
    End Function

    ' Returns a Scripting.Dictionary describing the order matching the given token, or Nothing if not found.
    Public Function FindByToken(token)
        Dim rs
        Set rs = DAL.Query( _
            "SELECT OrderID, Email, JurisdictionNumber, Token, TokenExpiresAt, TokenUsedAt, CreatedAt FROM Orders WHERE Token = ?", _
            Array(token))

        If rs.EOF Then
            Set FindByToken = Nothing
        Else
            Dim order : Set order = Server.CreateObject("Scripting.Dictionary")
            order.Add "OrderID", rs("OrderID").Value
            order.Add "Email", rs("Email").Value
            order.Add "JurisdictionNumber", rs("JurisdictionNumber").Value
            order.Add "Token", rs("Token").Value
            order.Add "TokenExpiresAt", rs("TokenExpiresAt").Value
            order.Add "TokenUsedAt", rs("TokenUsedAt").Value
            order.Add "CreatedAt", rs("CreatedAt").Value
            Set FindByToken = order
        End If

        Destroy rs
    End Function

    Public Sub MarkTokenUsed(orderId)
        DAL.Execute "UPDATE Orders SET TokenUsedAt = ? WHERE OrderID = ?", Array(Now(), orderId)
    End Sub

    Private Function TokenExpirationHours()
        Dim setting : setting = GetAppSetting("OrderTokenExpirationHours")
        If setting = "nothing" Or Not IsNumeric(setting) Then
            TokenExpirationHours = 24
        Else
            TokenExpirationHours = CInt(setting)
        End If
    End Function

End Class

Dim OrdersRepository__Singleton
Function OrdersRepository()
    If IsEmpty(OrdersRepository__Singleton) Then
        Set OrdersRepository__Singleton = New OrdersRepository_Class
    End If
    Set OrdersRepository = OrdersRepository__Singleton
End Function
%>
