// AgentValet SIEM streaming to Microsoft Sentinel.
// Same resources as agentvalet-sentinel.json (the ARM template is the one
// AgentValet's tests check; keep the column list identical).
// Creates, in YOUR subscription: a custom table in your Sentinel (Log
// Analytics) workspace, a Direct data collection rule for the Logs Ingestion
// API, and a Monitoring Metrics Publisher role assignment for the Entra app
// AgentValet signs in as. Deploy into the workspace's resource group:
//   az deployment group create -g <rg> -f agentvalet-sentinel.bicep \
//     -p workspaceName=<workspace> servicePrincipalObjectId=<sp-object-id>
// Docs: https://docs.agentvalet.ai/concepts/siem-streaming

@description('Name of the existing Log Analytics workspace that Microsoft Sentinel uses, in this resource group.')
param workspaceName string

@description('Object id of the service principal of the Entra app registration for AgentValet (az ad sp show --id <client-id> --query id -o tsv).')
param servicePrincipalObjectId string

@description('Region of the workspace. The DCR must be in the same region.')
param location string = resourceGroup().location

@description('Custom table name. Must end in _CL.')
param tableName string = 'AgentValet_CL'

@description('Name of the data collection rule to create.')
param dataCollectionRuleName string = 'dcr-agentvalet'

@description('Grant Monitoring Metrics Publisher on the DCR to the app. Needs Owner, User Access Administrator or Role Based Access Control Administrator. Set false if you only have Contributor, and have an Owner assign the role afterwards.')
param assignRole bool = true

var streamName = 'Custom-${tableName}'
var monitoringMetricsPublisher = '3913510d-42f4-4e42-8a64-420c390055eb'
var columns = [
  { name: 'TimeGenerated', type: 'datetime' }
  { name: 'EventUid', type: 'string' }
  { name: 'ClassUid', type: 'int' }
  { name: 'ClassName', type: 'string' }
  { name: 'CategoryUid', type: 'int' }
  { name: 'ActivityId', type: 'int' }
  { name: 'ActivityName', type: 'string' }
  { name: 'TypeUid', type: 'long' }
  { name: 'SeverityId', type: 'int' }
  { name: 'Severity', type: 'string' }
  { name: 'StatusId', type: 'int' }
  { name: 'Status', type: 'string' }
  { name: 'Message', type: 'string' }
  { name: 'AgentId', type: 'string' }
  { name: 'ParentAgentId', type: 'string' }
  { name: 'OrgId', type: 'string' }
  { name: 'OwnerId', type: 'string' }
  { name: 'PlatformId', type: 'string' }
  { name: 'Operation', type: 'string' }
  { name: 'Result', type: 'string' }
  { name: 'Reason', type: 'string' }
  { name: 'CorrelationUid', type: 'string' }
  { name: 'PolicyId', type: 'string' }
  { name: 'ApprovalId', type: 'string' }
  { name: 'PermissionId', type: 'string' }
  { name: 'OcsfVersion', type: 'string' }
  { name: 'Ocsf', type: 'dynamic' }
]

resource workspace 'Microsoft.OperationalInsights/workspaces@2022-10-01' existing = {
  name: workspaceName
}

resource table 'Microsoft.OperationalInsights/workspaces/tables@2022-10-01' = {
  parent: workspace
  name: tableName
  properties: {
    plan: 'Analytics'
    schema: {
      name: tableName
      columns: columns
    }
  }
}

resource dcr 'Microsoft.Insights/dataCollectionRules@2023-03-11' = {
  name: dataCollectionRuleName
  location: location
  kind: 'Direct'
  dependsOn: [table]
  properties: {
    description: 'AgentValet governance events (OCSF 1.3) via the Logs Ingestion API.'
    streamDeclarations: {
      '${streamName}': {
        columns: columns
      }
    }
    destinations: {
      logAnalytics: [
        {
          workspaceResourceId: workspace.id
          name: 'sentinelWorkspace'
        }
      ]
    }
    dataFlows: [
      {
        streams: [streamName]
        destinations: ['sentinelWorkspace']
        transformKql: 'source'
        outputStream: streamName
      }
    ]
  }
}

resource publisher 'Microsoft.Authorization/roleAssignments@2022-04-01' = if (assignRole) {
  scope: dcr
  name: guid(dcr.id, servicePrincipalObjectId, monitoringMetricsPublisher)
  properties: {
    roleDefinitionId: subscriptionResourceId('Microsoft.Authorization/roleDefinitions', monitoringMetricsPublisher)
    principalId: servicePrincipalObjectId
    principalType: 'ServicePrincipal'
  }
}

output logsIngestionEndpoint string = dcr.properties.endpoints.logsIngestion
output dcrImmutableId string = dcr.properties.immutableId
output streamName string = streamName
output dataCollectionRuleId string = dcr.id
