name: Trigger Microsoft Learn Docs Reference CI

on:
  release:
    types:
      - released

permissions:
  id-token: write

jobs:
  RunAzurePipeline:
    runs-on: ubuntu-latest
    environment: docs
    steps:
    - name: Azure Login
      uses: Azure/login@v2.1.0
      with:
        client-id: ${{ secrets.ADO_DocsReference_SP_ClientID }}
        tenant-id: ${{ secrets.ADO_DocsReference_SP_TenantID }}
        allow-no-subscriptions: true

    - name: Run Azure Pipeline
      shell: pwsh
      env: 
        AdoOrg: ${{secrets.ADO_DocsReference_Organization}}
        AdoProject: ${{secrets.ADO_DocsReference_Project}}
        AdoLatestPipelineId: ${{secrets.ADO_DocsReference_Latest_Pipeline_ID}}
        AdoLtsPipelineId: ${{secrets.ADO_DocsReference_LTS_Pipeline_ID}}
        ReleaseBranch: ${{ github.event.release.target_commitish }}
      run: |
          $organization = $env:AdoOrg
          $project = $env:AdoProject
          $thisRepoLink = "${{ github.server_url }}/${{ github.repository }}"
          $thisRunLink = "${{ github.server_url }}/${{ github.repository }}/actions/runs/${{ github.run_id }}"
          $triggerBranch = $env:ReleaseBranch
          $definitionId = $triggerBranch -eq 'release' ? $env:AdoLatestPipelineId : $env:AdoLtsPipelineId
          $variables = @("triggerBranch=$triggerBranch", "triggerFromRepo=$thisRepoLink", "triggerByPipeline=$thisRunLink")

          $output = az pipelines build queue --definition-id $definitionId --project $project --organization $organization --variables @variables | ConvertFrom-Json -AsHashtable
          if ($? -eq $false)
          {
              $pipelineDefinitionLink = $organization + [uri]::EscapeDataString($project) + "/_build?definitionId=$definitionId"
              Write-Error "Failed to queue the pipeline run for $pipelineDefinitionLink, please check above error message."
          }
          $runId = $output.id
          $runLink = $organization + [uri]::EscapeDataString($project) + "/_build/results?buildId=$runId"
          Write-Host "Triggered reference pipeline run, for details please check: $runLink"
