name: 'POI API - Deployment'
# this is triggered when there is a pull request on the below path, where the PR type is opened or reopened
on: 
  push:
    branches:
    - main
    paths:
    - 'apis/poi/**'
  workflow_dispatch:

env:
  GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}

#permissions:
#  contents: read

defaults:
  run:
    shell: bash
    working-directory: ./apis/poi/web

jobs:
  Build:
    name: 'Docker_Build_Deploy'
    runs-on: ubuntu-latest
    steps:
    # Checkout the repository to the GitHub Actions runner
    - name: Checkout
      uses: actions/checkout@v3
      
    - name: Set up Docker Buildx        
      uses: docker/setup-buildx-action@v2
      
    - name: "Azure Login"
      uses: Azure/login@v1
      with:
          creds: ${{ secrets.AZURE_CREDENTIALS }}
    
    - name: Build Docker Image
      run: 
        az acr build 
        --image devopsoh/api-poi:${{ github.run_id }}
        --registry devopsoh41379cr
        --build-arg build_version=${{ github.run_id }}
        --file Dockerfile .
        
    - name: Update_App_Service_Image_For_Staging_Slot
      run:
        az webapp config container set 
        --name devopsoh41379poi
        --resource-group devopsoh41379rg
        --slot staging
        --docker-custom-image-name devopsoh41379cr.azurecr.io/devopsoh/api-poi:${{ github.run_id }}
        --docker-registry-server-url https://devopsoh41379cr.azurecr.io

    - name: Stage Health Check
      uses: jtalk/url-health-check-action@v2
      with:
        # Check the following URLs one by one sequentially
        url: https://devopsoh41379poi-staging.azurewebsites.net/api/version/poi
        # Follow redirects, or just report success on 3xx status codes
        follow-redirect: false # Optional, defaults to "false"
        # Fail this action after this many failed attempts
        max-attempts: 3 # Optional, defaults to 1
        # Delay between retries
        retry-delay: 5s # Optional, only applicable to max-attempts > 1
        # Retry all errors, including 404. This option might trigger curl upgrade.
        retry-all: false # Optional, defaults to "false"

    - name: Swap into production
      run:
        az webapp deployment slot swap 
        --name devopsoh41379poi
        --resource-group devopsoh41379rg
        --action swap 
        --slot staging
        --target-slot production