name: Frontend Sourcemaps

on:
  workflow_dispatch:
  push:
    branches:
      - main
      - develop

jobs:
  upload-sourcemaps:
    runs-on:
      - self-hosted
      - linux
      - x64
    env:
      DATADOG_API_KEY: ${{ secrets.DATADOG_API_KEY }}
      DATADOG_SITE: datadoghq.com
      RELEASE_VERSION: ${{ github.sha }}
    steps:
      - name: Check out repository
        uses: actions/checkout@v6

      - name: Set up pnpm
        uses: pnpm/action-setup@v5
        with:
          version: 10.19.0

      - name: Set up Node.js
        uses: actions/setup-node@v6
        with:
          node-version: 22
          cache: pnpm

      - name: Validate Datadog secrets
        run: |
          test -n "$DATADOG_API_KEY"
          test -n "$DATADOG_SITE"

      - name: Install dependencies
        run: pnpm install --frozen-lockfile --child-concurrency=2

      - name: Build main
        run: pnpm --filter @xtablo/main build:prod
        env:
          VITE_APP_VERSION: ${{ env.RELEASE_VERSION }}

      - name: Upload main sourcemaps
        run: pnpm exec datadog-ci sourcemaps upload apps/main/dist --service xtablo-ui --release-version "$RELEASE_VERSION" --minified-path-prefix https://app.xtablo.com/assets

      - name: Remove main sourcemaps
        run: find apps/main/dist -name '*.map' -delete

      - name: Build clients
        run: pnpm --filter @xtablo/clients build:prod
        env:
          VITE_APP_VERSION: ${{ env.RELEASE_VERSION }}

      - name: Upload clients sourcemaps
        run: pnpm exec datadog-ci sourcemaps upload apps/clients/dist --service xtablo-clients --release-version "$RELEASE_VERSION" --minified-path-prefix https://clients.xtablo.com/assets

      - name: Remove clients sourcemaps
        run: find apps/clients/dist -name '*.map' -delete

      - name: Build external
        run: pnpm --filter @xtablo/external build
        env:
          VITE_APP_VERSION: ${{ env.RELEASE_VERSION }}

      - name: Upload external sourcemaps
        run: pnpm exec datadog-ci sourcemaps upload apps/external/dist --service xtablo-external --release-version "$RELEASE_VERSION" --minified-path-prefix https://embed.xtablo.com/assets

      - name: Remove external sourcemaps
        run: find apps/external/dist -name '*.map' -delete
