on:
  push:
    branches:
      - stage
      - prod

jobs:
  build:
    runs-on: docker

    steps:
      - name: Setup Bun
        uses: oven-sh/setup-bun@v1
        with:
          bun-version: 1.3.9

      - name: Checkout code
        uses: actions/checkout@v4

      - name: Cache bun modules
        uses: actions/cache@v4
        with:
          path: ~/.bun/install/cache
          key: ${{ runner.os }}-bun-${{ hashFiles('bun.lock') }}
          restore-keys: |
            ${{ runner.os }}-bun-

      - name: Install dependencies
        run: bun install --frozen-lockfile

      - name: Build Astro project
        run: bun run build

      - name: Deploy dist to dist-${{ env.FORGEJO_REF_NAME }}
        run: |
          git config --global user.name "forgejo-actions[bot]"
          git config --global user.email "forgejo-actions[bot]@users.noreply.local"

          git clone "https://x-access-token:${{ secrets.FORGEJO_TOKEN }}@git.workaround.org/${{ github.repository }}.git" repo
          cd repo
          git checkout dist-${{ env.FORGEJO_REF_NAME }} || git checkout --orphan dist-${{ env.FORGEJO_REF_NAME }}
          git rm -rf .
          
          # Copy dist files to repo directory
          cp -r ../dist/* ./
          
          git add .
          git commit -m "Update dist for ${{ env.FORGEJO_REF_NAME }}"
          git push origin dist-${{ env.FORGEJO_REF_NAME }} --force

      - name: Trigger deployment webhook
        env:
          DEPLOY_WEBHOOK: ${{ secrets.COOLIFY_DEPLOY_WEBHOOK }}
          DEPLOY_TOKEN: ${{ secrets.COOLIFY_DEPLOY_TOKEN }}
        run: |
          if [ "${{ env.FORGEJO_REF_NAME }}" = "stage" ]; then
            DEPLOY_WEBHOOK="${{ secrets.COOLIFY_DEPLOY_WEBHOOK_STAGE }}"
            DEPLOY_TOKEN="${{ secrets.COOLIFY_DEPLOY_TOKEN_STAGE }}"
          else
            DEPLOY_WEBHOOK="${{ secrets.COOLIFY_DEPLOY_WEBHOOK_PROD }}"
            DEPLOY_TOKEN="${{ secrets.COOLIFY_DEPLOY_TOKEN_PROD }}"
          fi

          curl -v "$DEPLOY_WEBHOOK" \
            --header "Authorization: Bearer $DEPLOY_TOKEN"
