name: Create and Push Agent TGZ to Main

on:
  push:
    branches:
      - main
    paths:
      - 'apps/agent/**'

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

      - name: Setup Node.js
        uses: actions/setup-node@v4
        with:
          node-version: '20'
      
      - name: Enable Corepack
        run: |
          corepack enable
          corepack prepare yarn@4.5.0 --activate

      - name: Install dependencies
        run: yarn install

      - name: Build and bundle
        run: |
          cd apps/agent
          yarn bundle

      - name: Rename bundle
        run: mv apps/agent/dist/*.tgz apps/agent/dist/agent-${{ github.sha }}.tgz
      
      - name: Create a copy with the name 'agent-latest.tgz'
        run: cp apps/agent/dist/agent-${{ github.sha }}.tgz apps/agent/dist/agent-latest.tgz

      - name: Upload artifact with SHA
        uses: actions/upload-artifact@v4
        with:
          name: agent-${{ github.sha }}.tgz
          path: apps/agent/dist/agent-${{ github.sha }}.tgz
          if-no-files-found: error
          retention-days: 1
          compression-level: 0

      - name: Upload artifact 'agent-latest.tgz'
        uses: actions/upload-artifact@v4
        with:
          name: agent-latest.tgz
          path: apps/agent/dist/agent-latest.tgz
          if-no-files-found: error
          retention-days: 1
          compression-level: 0