name: Preview (deploy)

on:
  workflow_run:
    workflows:
      - "Preview (build)"
    types:
      - completed

jobs:
  cache-compose-file:
    name: Cache Docker Compose file
    runs-on: ubuntu-latest
    if: ${{ github.event.workflow_run.conclusion == 'success' }}
    outputs:
      compose-file-cache-key: ${{ steps.hash.outputs.COMPOSE_FILE_HASH }}
      git-ref: ${{ steps.event.outputs.GIT_REF }}
      pr-number: ${{ steps.event.outputs.PR_NUMBER }}
      action: ${{ steps.event.outputs.ACTION }}
    steps:
      - name: "Download artifacts"
        # Fetch output (zip archive) from the workflow run that triggered this workflow.
        uses: actions/github-script@v6
        with:
          script: |
            let allArtifacts = await github.rest.actions.listWorkflowRunArtifacts({
               owner: context.repo.owner,
               repo: context.repo.repo,
               run_id: context.payload.workflow_run.id,
            });
            let matchArtifact = allArtifacts.data.artifacts.filter((artifact) => {
              return artifact.name == "preview-spec"
            })[0];
            if (matchArtifact === undefined) {
              throw TypeError('Build Artifact not found!');
            }
            let download = await github.rest.actions.downloadArtifact({
               owner: context.repo.owner,
               repo: context.repo.repo,
               artifact_id: matchArtifact.id,
               archive_format: 'zip',
            });
            let fs = require('fs');
            fs.writeFileSync(`${process.env.GITHUB_WORKSPACE}/preview-spec.zip`, Buffer.from(download.data));
      - name: "Unzip artifact"
        run: unzip preview-spec.zip event.json
      - name: Read Event into ENV
        id: event
        run: |
          echo PR_NUMBER=$(jq '.number | tonumber' < event.json) >> $GITHUB_OUTPUT
          echo ACTION=$(jq --raw-output '.action | tostring | [scan("\\w+")][0]' < event.json) >> $GITHUB_OUTPUT
          echo GIT_REF=$(jq --raw-output '.pull_request.head.sha | tostring | [scan("\\w+")][0]' < event.json) >> $GITHUB_OUTPUT
      - name: Hash Rendered Compose File
        id: hash
        # If the previous workflow was triggered by a PR close event, we will not have a compose file artifact.
        if: ${{ steps.event.outputs.ACTION != 'closed' }}
        run: |
          unzip preview-spec.zip docker-compose.rendered.yml
          echo "COMPOSE_FILE_HASH=$(md5sum docker-compose.rendered.yml | awk '{ print $1 }')" >> $GITHUB_OUTPUT
      - name: Cache Rendered Compose File
        if: ${{ steps.event.outputs.ACTION != 'closed' }}
        uses: actions/cache@v3
        with:
          path: docker-compose.rendered.yml
          key: ${{ steps.hash.outputs.COMPOSE_FILE_HASH }}

      - name: DEBUG - Print Job Outputs
        if: ${{ runner.debug }}
        run: |
          echo "PR number: ${{ steps.event.outputs.PR_NUMBER }}"
          echo "Git Ref: ${{ steps.event.outputs.GIT_REF }}"
          echo "Action: ${{ steps.event.outputs.ACTION }}"
          echo "Compose file hash: ${{ steps.hash.outputs.COMPOSE_FILE_HASH }}"
          cat event.json

  deploy-uffizzi-preview:
    name: Run Uffizzi deployment
    needs:
      - cache-compose-file
    if: ${{ github.event.workflow_run.conclusion == 'success' }}
    uses: UffizziCloud/preview-action/.github/workflows/reusable.yaml@v2
    with:
      # If this workflow was triggered by a PR close event, cache-key will be an empty string
      # and this reusable workflow will delete the preview deployment.
      compose-file-cache-key: ${{ needs.cache-compose-file.outputs.compose-file-cache-key }}
      compose-file-cache-path: docker-compose.rendered.yml
      server: https://app.uffizzi.com
      pr-number: ${{ needs.cache-compose-file.outputs.pr-number }}
    permissions:
      contents: read
      pull-requests: write
      id-token: write
