name: Deploy to Production, build images and push to Gitea Registry

on:
  pull_request:
    types: [closed]
    branches:
      - prod

jobs:
  build_and_push:
    if: github.event.pull_request.merged == true
    runs-on: ubuntu-latest

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

      - name: Set up Docker Buildx
        uses: docker/setup-buildx-action@v3

      - name: Debug context variables
        run: |
          echo "Actor: ${{ gitea.actor }}"
          echo "Repository: ${{ gitea.repository_name }}"
          echo "Repository owner: ${{ gitea.repository_owner }}"
          echo "Event repository name: ${{ gitea.event.repository.name }}"
          echo "Event repository full name: ${{ gitea.event.repository.full_name }}"
          echo "Event repository owner login: ${{ gitea.event.repository.owner.login }}"

      - name: Login to Gitea Registry
        env:
          GITEA_USERNAME: ${{ secrets.ME_USERNAME }}
          GITEA_PASSWORD: ${{ secrets.ME_PASSWORD }}
        run: |
          echo $GITEA_PASSWORD | docker login git.vinylnostalgia.com -u $GITEA_USERNAME --password-stdin

      - name: Set repository variables
        id: vars
        run: |
          REPO_NAME="${{ gitea.repository_name }}"
          ACTOR="${{ gitea.actor }}"
          
          # Use fallback if variables are empty
          if [ -z "$REPO_NAME" ]; then
            REPO_NAME="${{ gitea.event.repository.name }}"
          fi
          if [ -z "$ACTOR" ]; then
            ACTOR="${{ gitea.event.repository.owner.login }}"
          fi
          
          echo "actor=$ACTOR" >> $GITHUB_OUTPUT
          echo "repo_name=$REPO_NAME" >> $GITHUB_OUTPUT
          echo "Using ACTOR: $ACTOR"
          echo "Using REPO_NAME: $REPO_NAME"

      - name: Build backend image with optimizations
        env:
          GITEA_USERNAME: ${{ secrets.ME_USERNAME }}
          GITEA_PASSWORD: ${{ secrets.ME_PASSWORD }}
        run: |
          REPO_NAME="${{ gitea.repository_name }}"
          ACTOR="${{ gitea.actor }}"
          
          # Use fallback if variables are empty
          if [ -z "$REPO_NAME" ]; then
            REPO_NAME="${{ gitea.event.repository.name }}"
          fi
          if [ -z "$ACTOR" ]; then
            ACTOR="${{ gitea.event.repository.owner.login }}"
          fi
          
          echo "Building backend image..."
          echo "Using ACTOR: $ACTOR"
          echo "Using REPO_NAME: $REPO_NAME"
          
          # Build with BuildKit optimizations
          DOCKER_BUILDKIT=1 docker build \
            --compress \
            --no-cache \
            --squash \
            --build-arg BUILDKIT_INLINE_CACHE=1 \
            -t git.vinylnostalgia.com/$ACTOR/$REPO_NAME-backend:latest \
            ./be -f ./be/Dockerfile.prod
          
          echo "Backend image built successfully"

      - name: Push backend image with retry logic
        env:
          GITEA_USERNAME: ${{ secrets.ME_USERNAME }}
          GITEA_PASSWORD: ${{ secrets.ME_PASSWORD }}
        run: |
          REPO_NAME="${{ gitea.repository_name }}"
          ACTOR="${{ gitea.actor }}"
          
          # Use fallback if variables are empty
          if [ -z "$REPO_NAME" ]; then
            REPO_NAME="${{ gitea.event.repository.name }}"
          fi
          if [ -z "$ACTOR" ]; then
            ACTOR="${{ gitea.event.repository.owner.login }}"
          fi
          
          # Push with retries and compression
          max_retries=5
          retry_count=0
          base_wait=10
          
          while [ $retry_count -lt $max_retries ]; do
            echo "Pushing backend image (attempt $((retry_count + 1)) of $max_retries)..."
            
            if docker push git.vinylnostalgia.com/$ACTOR/$REPO_NAME-backend:latest; then
              echo "Backend image pushed successfully"
              break
            fi
            
            retry_count=$((retry_count + 1))
            if [ $retry_count -lt $max_retries ]; then
              wait_time=$((base_wait * retry_count))
              echo "Push failed, retrying in $wait_time seconds..."
              sleep $wait_time
            fi
          done
          
          if [ $retry_count -eq $max_retries ]; then
            echo "Failed to push backend image after $max_retries attempts"
            exit 1
          fi

      - name: Build frontend image with optimizations
        env:
          GITEA_USERNAME: ${{ secrets.ME_USERNAME }}
          GITEA_PASSWORD: ${{ secrets.ME_PASSWORD }}
        run: |
          REPO_NAME="${{ gitea.repository_name }}"
          ACTOR="${{ gitea.actor }}"
          
          # Use fallback if variables are empty
          if [ -z "$REPO_NAME" ]; then
            REPO_NAME="${{ gitea.event.repository.name }}"
          fi
          if [ -z "$ACTOR" ]; then
            ACTOR="${{ gitea.event.repository.owner.login }}"
          fi
          
          echo "Building frontend image..."
          echo "Using ACTOR: $ACTOR"
          echo "Using REPO_NAME: $REPO_NAME"
          
          # Build with BuildKit optimizations
          DOCKER_BUILDKIT=1 docker build \
            --compress \
            --no-cache \
            --squash \
            --build-arg BUILDKIT_INLINE_CACHE=1 \
            -t git.vinylnostalgia.com/$ACTOR/$REPO_NAME-frontend:latest \
            ./fe -f ./fe/Dockerfile.prod
          
          echo "Frontend image built successfully"

      - name: Push frontend image with retry logic
        env:
          GITEA_USERNAME: ${{ secrets.ME_USERNAME }}
          GITEA_PASSWORD: ${{ secrets.ME_PASSWORD }}
        run: |
          REPO_NAME="${{ gitea.repository_name }}"
          ACTOR="${{ gitea.actor }}"
          
          # Use fallback if variables are empty
          if [ -z "$REPO_NAME" ]; then
            REPO_NAME="${{ gitea.event.repository.name }}"
          fi
          if [ -z "$ACTOR" ]; then
            ACTOR="${{ gitea.event.repository.owner.login }}"
          fi
          
          # Push with retries and exponential backoff
          max_retries=5
          retry_count=0
          base_wait=10
          
          while [ $retry_count -lt $max_retries ]; do
            echo "Pushing frontend image (attempt $((retry_count + 1)) of $max_retries)..."
            
            if docker push git.vinylnostalgia.com/$ACTOR/$REPO_NAME-frontend:latest; then
              echo "Frontend image pushed successfully"
              break
            fi
            
            retry_count=$((retry_count + 1))
            if [ $retry_count -lt $max_retries ]; then
              wait_time=$((base_wait * retry_count))
              echo "Push failed, retrying in $wait_time seconds..."
              sleep $wait_time
            fi
          done
          
          if [ $retry_count -eq $max_retries ]; then
            echo "Failed to push frontend image after $max_retries attempts"
            exit 1
          fi

      - name: Cleanup Docker resources
        if: always()
        run: |
          echo "Cleaning up Docker resources..."
          docker system prune -af --volumes
          docker logout git.vinylnostalgia.com
          echo "Cleanup completed"

      - name: Show final image sizes
        if: always()
        run: |
          echo "Final image sizes:"
          docker images --format "table {{.Repository}}\t{{.Tag}}\t{{.Size}}" | grep -E "(vinylnostalgia|REPOSITORY)"