name: Deploy to Environment
on:
  workflow_dispatch:
    inputs:
      environment:
        description: 'Environment'
        required: true

  repository_dispatch:
    types: [deployer-event]

jobs:
  checks:
    runs-on: ubuntu-latest
    name: "Check branch details"
    if: "!contains(github.event.head_commit.message, '[skip ci]')"
    outputs:
      branch: ${{ steps.myref.outputs.branch }}
      target: ${{ steps.myref.outputs.target }}
      environment: ${{ steps.myref.outputs.environment }}
    steps:
    - name: Determine dispatch or push branch details
      shell: bash
      run: |
        #!/bin/bash
        set -x
        if [ $GITHUB_EVENT_NAME == "repository_dispatch" ]; then
          echo "dispatch event"
          echo "::set-output name=branch::${{ github.event.client_payload.branch }}"
          echo "::set-output name=environment::${{github.event.client_payload.env}}"
          echo "::set-output name=target::$(echo \"${{ github.event.client_payload.env }}\" | sed 's/-//g')"
        else
          echo "push event"
          echo "::set-output name=branch::${GITHUB_REF#refs/heads/}"
          echo "::set-output name=environment::${{github.event.inputs.environment}}"
          echo "::set-output name=target::$(echo \"${{ github.event.inputs.environment }}\" | sed 's/-//g')"
        fi

      id: myref

    - name: Print deployment environment details
      run: |
        echo "Branch: ${{ steps.myref.outputs.branch }}"
        echo "Previewer Target: ${{ steps.myref.outputs.target }}"
        echo "Environment: ${{ steps.myref.outputs.environment }}"

  build:
    needs: [checks]
    runs-on: ubuntu-latest
    name: "Build runner"
    steps:
    - uses: actions/checkout@v2
      with:
        ref: ${{ needs.checks.outputs.branch }}

    - name: Setup Node.js
      uses: actions/setup-node@v4
      with:
        node-version: 18

    - name: Installing dependencies
      run: yarn install --frozen-lockfile

    - name: Build lib
      run: yarn run compile

  deploy:
    needs: [checks,build]
    runs-on: ubuntu-latest
    name: "Deploy Web Preview"
    steps:
    - uses: peter-evans/repository-dispatch@v1
      with:
        token: ${{secrets.GH_ACTIONS_TOKEN}}
        repository: AdaloHQ/web-preview
        event-type: deployer-event
        client-payload: '{"sha": "${{ github.sha }}", "branch": "${{ needs.checks.outputs.branch }}", "env": "${{ needs.checks.outputs.environment }}"}'

  post:
    needs: [deploy]
    runs-on: ubuntu-latest
    name: Check web-preview dispatch
    steps:
      - name: "Get dispatch id"
        uses: octokit/request-action@v2.1.0
        id: get_latest_repository_dispatch
        with:
          route: "GET /repos/AdaloHQ/web-preview/actions/runs?event=repository_dispatch&per_page=1"
        env:
          GITHUB_TOKEN: ${{ secrets.GH_ACTIONS_TOKEN }}

      - name: "Wait for dispatch success"
        id: check_dispatch_status
        shell: bash {0}
        run: |
            counter=0
            conclusion="in_progress"
            while [[ $conclusion == null || $conclusion == "in_progress" ]]
            do
              if [[ "$counter" -ge "60" ]]; then
                echo "Time limit exceeded"
                exit 1
              fi
              if [[ "$counter" -ge "1" ]]; then
                sleep 20
              fi
              conclusion=$(curl -s "https://api.github.com/repos/AdaloHQ/web-preview/actions/runs/${{ fromJson(steps.get_latest_repository_dispatch.outputs.data).workflow_runs[0].id }}" \
              	-H "Accept: application/vnd.github.v3+json" \
              	-H "Authorization: Bearer ${{ secrets.GH_ACTIONS_TOKEN }}" | jq '.conclusion')
              counter=$(( $counter + 1 ))
            done
            if [[ $conclusion == "\"success\"" ]]
            then
              echo "Workflow run successful"
            else
              echo "Workflow run failed"
              exit 1
            fi
