name: Deploy Staging

on:
  push:
    branches:
      - hetzner/staging

concurrency:
  group: deploy-frontend-staging
  cancel-in-progress: false

env:
  ANSIBLE_FORCE_COLOR: true
  TARGET_PLATFORMS: linux/arm64
  NODE_ENV: production

jobs:
  build:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4

      - uses: actions/setup-node@v4
        with:
          node-version: 22.x
          cache: yarn

      - name: Install dependencies
        run: yarn install --frozen-lockfile --prefer-offline --production=false

      - name: Turbo Cache
        uses: actions/cache@v4
        with:
          path: .turbo
          key: turbo-build-${{ github.job }}-${{ github.ref_name }}-${{ github.sha }}
          restore-keys: |
            turbo-build-${{ github.job }}-${{ github.ref_name }}-

      - name: Build packages
        run: yarn build
        env:
          PUBLIC_VITE_APP_ENV: staging
          PUBLIC_VITE_API_URL: https://staging.dashhub.ai/api
          PUBLIC_VITE_DIRECTUS_URL: https://staging.dashhub.ai/cms

      - name: Upload build artifacts
        uses: actions/upload-artifact@v4
        with:
          name: staging-build-artifacts
          overwrite: true
          retention-days: 1
          path: |
            apps/*/dist
            packages/*/dist

  deploy-docker-images:
    needs: build
    runs-on: ubuntu-latest
    strategy:
      matrix:
        app:
          - name: frontend
            context: apps/frontend
          - name: backend
            context: apps/backend
          - name: admin
            context: apps/admin
          - name: chat
            context: apps/chat
    steps:
      - uses: actions/checkout@v4
      - uses: docker/setup-qemu-action@v3
      - uses: docker/setup-buildx-action@v3

      - name: Download build artifacts
        uses: actions/download-artifact@v4
        with:
          name: staging-build-artifacts

      - uses: docker/login-action@v3
        with:
          registry: staging.dashhub.ai
          username: ${{ secrets.STAGING_PODMAN_REGISTRY_USERNAME }}
          password: ${{ secrets.STAGING_PODMAN_REGISTRY_PASSWORD }}

      - uses: docker/build-push-action@v6
        with:
          context: ${{ matrix.app.context }}
          push: true
          tags: |
            staging.dashhub.ai/dashhub-${{ matrix.app.name }}:latest
            staging.dashhub.ai/dashhub-${{ matrix.app.name }}:${{ github.sha }}
          platforms: ${{ env.TARGET_PLATFORMS }}
          cache-from: type=gha,scope=${{ matrix.app.name }}
          cache-to: type=gha,scope=${{ matrix.app.name }},mode=max
