name: Feature Branch Deployment

on:
  pull_request:
    # branches: [dev, staging, prod, main]  # filter according to the PR target branch
    types: [opened, synchronize, reopened]

env:
  IMAGE_TAG: 'aulaapp/aula-frontend:pr-${{ github.event.number }}'
  PR_NUMBER: ${{ github.event.number }}

jobs:
  build:
    runs-on: [self-hosted, cicd]
    steps:
      - name: Checkout code
        uses: actions/checkout@v4

      - name: Set up Docker Buildx
        uses: docker/setup-buildx-action@v3

      - name: Build Docker image
        run: docker build --build-arg DOCKER_TAG=$IMAGE_TAG --build-arg "VITE_APP_BASENAME=/$PR_NUMBER/" -t $IMAGE_TAG .

      - name: Push Docker image
        run: docker push $IMAGE_TAG

  deploy-dev:
    if: ${{ !contains(fromJSON('["main", "dev", "staging", "prod"]'), github.head_ref) }}
    runs-on: [self-hosted, dev]
    needs: build
    continue-on-error: true
    steps:
      - name: Check if branch still exists (PR can be closed if the build takes long time)
        id: check_branch
        run: |
          RESPONSE=$(curl -s -o /dev/null -w "%{http_code}" \
            -H "Authorization: token ${{ secrets.GITHUB_TOKEN }}" \
            "https://api.github.com/repos/${{ github.repository }}/git/refs/heads/${{ github.head_ref }}")
          if [ "$RESPONSE" -ne 200 ]; then
            echo "Branch does not exist. Exiting."
            exit 1
          fi

      - uses: actions/checkout@v4
        with:
          sparse-checkout: |
            docker-compose.pr.yml
          sparse-checkout-cone-mode: false

      - name: Pull the latest version
        run: docker compose -f ./docker-compose.pr.yml pull

      - name: Deploy to dev Branch Testing Environment
        run: docker compose -f ./docker-compose.pr.yml up -d

  deploy-staging:
    if: ${{ !contains(fromJSON('["main", "dev", "staging", "prod"]'), github.head_ref) }}
    runs-on: [self-hosted, staging]
    needs: build
    continue-on-error: true
    steps:
      - name: Check if branch still exists (PR can be closed if the build takes long time)
        id: check_branch
        run: |
          RESPONSE=$(curl -s -o /dev/null -w "%{http_code}" \
            -H "Authorization: token ${{ secrets.GITHUB_TOKEN }}" \
            "https://api.github.com/repos/${{ github.repository }}/git/refs/heads/${{ github.head_ref }}")
          if [ "$RESPONSE" -ne 200 ]; then
            echo "Branch does not exist. Exiting."
            exit 1
          fi

      - uses: actions/checkout@v4
        with:
          sparse-checkout: |
            docker-compose.pr.yml
          sparse-checkout-cone-mode: false

      - name: Pull the latest version
        run: docker compose -f ./docker-compose.pr.yml pull

      - name: Deploy to staging Branch Testing Environment
        run: docker compose -f ./docker-compose.pr.yml up -d
