name: Deploy Stacks

on:
  push:
    branches:
      - main
      - dev
      - staging
  workflow_dispatch:

concurrency:
  group: deploy-${{ github.ref_name }}
  cancel-in-progress: true

jobs:
  deploy:
    name: Deploy ${{ matrix.service }}
    runs-on: self-hosted
    strategy:
      fail-fast: false
      matrix:
        include:
          - project: ema-dev
            build_env_file: portal-web.build.env
            service: ema-portal
          - project: ema-dev
            build_env_file: backoffice-web.build.env
            service: ema-backoffice
    env:
      PROJECT: ${{ matrix.project }}
      BRANCH: ${{ github.ref_name }}
      DEPLOY_USER: tria
      BUILD_ENV_FILE: ${{ matrix.build_env_file }}
      DOCKER_BUILDKIT: "1"
      COMPOSE_DOCKER_CLI_BUILD: "1"
    steps:
      - name: Checkout
        uses: actions/checkout@v4

      - name: Sync environment from server
        run: |
          chmod +x scripts/deploy/*.sh
          ./scripts/deploy/sync-env-from-server.sh "${{ matrix.service }}"

      - name: Set compose project name
        run: |
          set -euo pipefail
          branch_slug=$(echo "${BRANCH}" | tr "[:upper:]" "[:lower:]" | sed -E "s/[^a-z0-9]+/-/g; s/^-+//; s/-+$//")
          echo "COMPOSE_PROJECT_NAME=${PROJECT}-${branch_slug}" >> "${GITHUB_ENV}"

      - name: Configure npm auth for Docker builds
        env:
          NPM_TOKEN: ${{ secrets.NPM_TOKEN }}
        run: ./scripts/deploy/create-npmrc.sh

      - name: Build ${{ matrix.service }}
        run: |
          set -euo pipefail
          docker compose --project-name "${COMPOSE_PROJECT_NAME}" build --no-cache "${{ matrix.service }}"

      - name: Deploy ${{ matrix.service }}
        run: |
          set -euo pipefail
          docker compose --project-name "${COMPOSE_PROJECT_NAME}" up -d "${{ matrix.service }}"

      - name: Remove npm credentials from workspace
        if: always()
        run: rm -f .npmrc .npmrc_temp
