name: Build and Deploy Build Output

on:
  push:
    branches: [ main ]
  pull_request:
    branches: [ main ]

jobs:
  build:
    runs-on: ubuntu-latest

    steps:
      - name: Checkout repository
        uses: actions/checkout@v3

      - name: Setup Node.js
        uses: actions/setup-node@v3
        with:
          node-version: '18.17.0'

      - name: Install dependencies
        run: npm install

      - name: Build Next.js project
        run: npm run build

      # Optional: List build directories to verify output exists
      - name: List build directories
        run: ls -la

      - name: Deploy build output to build-output branch
        env:
          # The GITHUB_TOKEN is automatically provided by GitHub Actions.
          GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
        run: |
          # Configure git
          git config --global user.name "GitHub Actions"
          git config --global user.email "actions@github.com"
          
          # Create a temporary directory for the output
          mkdir deploy
          # Copy the build outputs (update the paths if needed)
          cp -r out deploy/
          cp -r .next deploy/ 2>/dev/null || echo ".next folder not found, skipping."

          # Move into the deploy directory
          cd deploy
          
          # Initialize a new git repo
          git init
          git checkout -b build-output
          
          # Add all files and commit them
          git add .
          git commit -m "Deploy build output for commit ${GITHUB_SHA}"
          
          # Force push to the remote build-output branch
          git push --force "https://x-access-token:${GITHUB_TOKEN}@github.com/${{ github.repository }}.git" build-output
