{
    "$schema": "https://schema.management.azure.com/schemas/2019-04-01/deploymentTemplate.json#",
    "contentVersion": "1.0.0.0",
    "parameters": {
        "logicAppName": {
            "type": "string",
            "defaultValue": "la-kiteworks-pubsub",
            "metadata": {
                "description": "Name of the Logic App"
            }
        },
        "dceName": {
            "type": "string",
            "defaultValue": "dce-kiteworks-pubsub",
            "metadata": {
                "description": "Name of the Data Collection Endpoint"
            }
        },
        "dcrName": {
            "type": "string",
            "defaultValue": "dcr-kiteworks-pubsub",
            "metadata": {
                "description": "Name of the Data Collection Rule"
            }
        },
        "workspaceResourceId": {
            "type": "string",
            "metadata": {
                "description": "Resource ID of the Log Analytics Workspace. Find it in Azure Portal > Log Analytics workspace > Properties > Resource ID. Format: /subscriptions/<sub-id>/resourceGroups/<rg>/providers/Microsoft.OperationalInsights/workspaces/<name>"
            }
        },
        "workspaceName": {
            "type": "string",
            "metadata": {
                "description": "Name of the Log Analytics Workspace (just the name, not the full resource ID)"
            }
        },
        "location": {
            "type": "string",
            "defaultValue": "[resourceGroup().location]"
        }
    },
    "variables": {
        "tableName": "KwPubSub_CL",
        "streamName": "Custom-KwPubSub_CL",
        "monitoringMetricsPublisherRoleId": "3913510d-42f4-4e42-8a64-420c390055eb",
        "roleAssignmentName": "[guid(resourceId('Microsoft.Logic/workflows', parameters('logicAppName')), variables('monitoringMetricsPublisherRoleId'), resourceId('Microsoft.Insights/dataCollectionRules', parameters('dcrName')))]"
    },
    "resources": [
        {
            "type": "Microsoft.OperationalInsights/workspaces/tables",
            "apiVersion": "2022-10-01",
            "name": "[concat(parameters('workspaceName'), '/', variables('tableName'))]",
            "properties": {
                "schema": {
                    "name": "[variables('tableName')]",
                    "columns": [
                        { "name": "TimeGenerated", "type": "datetime" },
                        { "name": "sourceTenantId", "type": "string" },
                        { "name": "webhookId", "type": "string" },
                        { "name": "payload_client_device", "type": "string" },
                        { "name": "payload_client_id", "type": "string" },
                        { "name": "payload_client_name", "type": "string" },
                        { "name": "payload_created", "type": "real" },
                        { "name": "payload_data", "type": "dynamic" },
                        { "name": "payload_data_keywords", "type": "string" },
                        { "name": "payload_domain", "type": "string" },
                        { "name": "payload_endpoint", "type": "string" },
                        { "name": "payload_endpoint_version", "type": "string" },
                        { "name": "payload_event_id", "type": "int" },
                        { "name": "payload_event_name", "type": "string" },
                        { "name": "payload_flag", "type": "int" },
                        { "name": "payload_geolocation_id", "type": "int" },
                        { "name": "payload_guid", "type": "string" },
                        { "name": "payload_host", "type": "string" },
                        { "name": "payload_indirect_users", "type": "string" },
                        { "name": "payload_ip_address", "type": "string" },
                        { "name": "payload_node_ip", "type": "string" },
                        { "name": "payload_node_storage_id", "type": "string" },
                        { "name": "payload_parent_folder_id", "type": "string" },
                        { "name": "payload_single_line", "type": "string" },
                        { "name": "payload_successful", "type": "boolean" },
                        { "name": "payload_tenant_id", "type": "int" },
                        { "name": "payload_transaction_id", "type": "string" },
                        { "name": "payload_user_agent", "type": "string" },
                        { "name": "payload_user_id", "type": "int" },
                        { "name": "payload_username", "type": "string" }
                    ]
                },
                "retentionInDays": 90,
                "plan": "Analytics"
            }
        },
        {
            "type": "Microsoft.Insights/dataCollectionEndpoints",
            "apiVersion": "2022-06-01",
            "name": "[parameters('dceName')]",
            "location": "[parameters('location')]",
            "properties": {
                "networkAcls": {
                    "publicNetworkAccess": "Enabled"
                }
            }
        },
        {
            "type": "Microsoft.Insights/dataCollectionRules",
            "apiVersion": "2022-06-01",
            "name": "[parameters('dcrName')]",
            "location": "[parameters('location')]",
            "dependsOn": [
                "[resourceId('Microsoft.Insights/dataCollectionEndpoints', parameters('dceName'))]",
                "[resourceId('Microsoft.OperationalInsights/workspaces/tables', parameters('workspaceName'), variables('tableName'))]"
            ],
            "properties": {
                "dataCollectionEndpointId": "[resourceId('Microsoft.Insights/dataCollectionEndpoints', parameters('dceName'))]",
                "streamDeclarations": {
                    "Custom-KwPubSub_CL": {
                        "columns": [
                            { "name": "TimeGenerated", "type": "datetime" },
                            { "name": "tenantId", "type": "string" },
                            { "name": "webhookId", "type": "string" },
                            { "name": "payload", "type": "dynamic" }
                        ]
                    }
                },
                "dataSources": {},
                "destinations": {
                    "logAnalytics": [
                        {
                            "workspaceResourceId": "[parameters('workspaceResourceId')]",
                            "name": "workspace"
                        }
                    ]
                },
                "dataFlows": [
                    {
                        "streams": [ "Custom-KwPubSub_CL" ],
                        "destinations": [ "workspace" ],
                        "transformKql": "source | extend TimeGenerated = now(), sourceTenantId = tostring(tenantId), webhookId = tostring(webhookId), payload_client_device = tostring(payload.client_device), payload_client_id = tostring(payload.client_id), payload_client_name = tostring(payload.client_name), payload_created = todouble(payload.created), payload_data = todynamic(tostring(payload.data)), payload_data_keywords = tostring(payload.data_keywords), payload_domain = tostring(payload.domain), payload_endpoint = tostring(payload.endpoint), payload_endpoint_version = tostring(payload.endpoint_version), payload_event_id = toint(payload.event_id), payload_event_name = tostring(payload.event_name), payload_flag = toint(payload.flag), payload_geolocation_id = toint(payload.geolocation_id), payload_guid = tostring(payload.guid), payload_host = tostring(payload.host), payload_indirect_users = tostring(payload.indirect_users), payload_ip_address = tostring(payload.ip_address), payload_node_ip = tostring(payload.node_ip), payload_node_storage_id = tostring(payload.node_storage_id), payload_parent_folder_id = tostring(payload.parent_folder_id), payload_single_line = tostring(payload.single_line), payload_successful = tobool(payload.successful), payload_tenant_id = toint(payload.tenant_id), payload_transaction_id = tostring(payload.transaction_id), payload_user_agent = tostring(payload.user_agent), payload_user_id = toint(payload.user_id), payload_username = tostring(payload.username) | project-away payload",
                        "outputStream": "Custom-KwPubSub_CL"
                    }
                ]
            }
        },
        {
            "type": "Microsoft.Logic/workflows",
            "apiVersion": "2019-05-01",
            "name": "[parameters('logicAppName')]",
            "location": "[parameters('location')]",
            "dependsOn": [
                "[resourceId('Microsoft.Insights/dataCollectionEndpoints', parameters('dceName'))]",
                "[resourceId('Microsoft.Insights/dataCollectionRules', parameters('dcrName'))]"
            ],
            "identity": {
                "type": "SystemAssigned"
            },
            "properties": {
                "state": "Enabled",
                "definition": {
                    "$schema": "https://schema.management.azure.com/providers/Microsoft.Logic/schemas/2016-06-01/workflowdefinition.json#",
                    "contentVersion": "1.0.0.0",
                    "triggers": {
                        "Webhook_Consumer": {
                            "type": "Request",
                            "kind": "Http"
                        }
                    },
                    "actions": {
                        "Send_to_Logs_Ingestion_API": {
                            "type": "Http",
                            "inputs": {
                                "uri": "@{parameters('dceEndpoint')}/dataCollectionRules/@{parameters('dcrImmutableId')}/streams/@{parameters('streamName')}?api-version=2023-01-01",
                                "method": "POST",
                                "headers": {
                                    "Content-Type": "application/json"
                                },
                                "body": "@createArray(triggerBody())",
                                "authentication": {
                                    "type": "ManagedServiceIdentity",
                                    "audience": "https://monitor.azure.com"
                                }
                            },
                            "runAfter": {}
                        }
                    },
                    "outputs": {},
                    "parameters": {
                        "dceEndpoint": {
                            "type": "String",
                            "defaultValue": ""
                        },
                        "dcrImmutableId": {
                            "type": "String",
                            "defaultValue": ""
                        },
                        "streamName": {
                            "type": "String",
                            "defaultValue": ""
                        }
                    }
                },
                "parameters": {
                    "dceEndpoint": {
                        "type": "String",
                        "value": "[reference(resourceId('Microsoft.Insights/dataCollectionEndpoints', parameters('dceName')), '2022-06-01').logsIngestion.endpoint]"
                    },
                    "dcrImmutableId": {
                        "type": "String",
                        "value": "[reference(resourceId('Microsoft.Insights/dataCollectionRules', parameters('dcrName')), '2022-06-01').immutableId]"
                    },
                    "streamName": {
                        "type": "String",
                        "value": "[variables('streamName')]"
                    }
                }
            }
        },
        {
            "type": "Microsoft.Insights/dataCollectionRules/providers/roleAssignments",
            "apiVersion": "2022-04-01",
            "name": "[concat(parameters('dcrName'), '/Microsoft.Authorization/', variables('roleAssignmentName'))]",
            "dependsOn": [
                "[resourceId('Microsoft.Logic/workflows', parameters('logicAppName'))]",
                "[resourceId('Microsoft.Insights/dataCollectionRules', parameters('dcrName'))]"
            ],
            "properties": {
                "roleDefinitionId": "[subscriptionResourceId('Microsoft.Authorization/roleDefinitions', variables('monitoringMetricsPublisherRoleId'))]",
                "principalId": "[reference(resourceId('Microsoft.Logic/workflows', parameters('logicAppName')), '2019-05-01', 'full').identity.principalId]",
                "principalType": "ServicePrincipal"
            }
        }
    ],
    "outputs": {
        "logicAppCallbackUrl": {
            "type": "string",
            "value": "[listCallbackUrl(resourceId('Microsoft.Logic/workflows/triggers', parameters('logicAppName'), 'Webhook_Consumer'), '2019-05-01').value]"
        },
        "dcrImmutableId": {
            "type": "string",
            "value": "[reference(resourceId('Microsoft.Insights/dataCollectionRules', parameters('dcrName')), '2022-06-01').immutableId]"
        }
    }
}
