name: Build, Tag and Push Docker Image

on:
  push:
    branches:
      - main
      - dev
  pull_request:
    branches:
      - main

jobs:
  build-and-push:
    runs-on: ubuntu-latest

    steps:
      - name: Checkout code
        uses: actions/checkout@v4
        with:
          fetch-depth: 0

      - name: Determine version and create tag (main only)
        id: version
        run: |
          if [ "${{ gitea.ref_name }}" = "main" ]; then
            # Hole letzten Tag
            LATEST_TAG=$(git tag -l "v*" --sort=-v:refname | head -n 1)
          
            if [ -z "$LATEST_TAG" ]; then
              NEW_TAG="v1.0.0"
              BUMP="minor"
            else
              VERSION=${LATEST_TAG#v}
              MAJOR=$(echo $VERSION | cut -d. -f1)
              MINOR=$(echo $VERSION | cut -d. -f2)
              PATCH=$(echo $VERSION | cut -d. -f3)
          
              COMMITS=$(git log ${LATEST_TAG}..HEAD --pretty=format:"%s" 2>/dev/null || echo "")
          
              if [ -z "$COMMITS" ]; then
                echo "Keine neuen Commits seit ${LATEST_TAG}"
                echo "skip=true" >> $GITHUB_OUTPUT
                echo "version=${VERSION}" >> $GITHUB_OUTPUT
                exit 0
              fi
          
              if echo "$COMMITS" | grep -qiE "^BREAKING CHANGE:|^[^:]+!:|breaking:|major:"; then
                MAJOR=$((MAJOR + 1)); MINOR=0; PATCH=0; BUMP="major"
              elif echo "$COMMITS" | grep -qiE "^feat:|^feature:|minor:"; then
                MINOR=$((MINOR + 1)); PATCH=0; BUMP="minor"
              else
                PATCH=$((PATCH + 1)); BUMP="patch"
              fi
          
              NEW_TAG="v${MAJOR}.${MINOR}.${PATCH}"
            fi
          
            # Prüfe ob Tag bereits existiert
            if git rev-parse "$NEW_TAG" >/dev/null 2>&1; then
              echo "Tag ${NEW_TAG} existiert bereits"
              echo "skip=true" >> $GITHUB_OUTPUT
              echo "version=${NEW_TAG#v}" >> $GITHUB_OUTPUT
            else
              echo "Erstelle neues Tag: ${NEW_TAG} (${BUMP})"
              echo "new_tag=${NEW_TAG}" >> $GITHUB_OUTPUT
              echo "version=${NEW_TAG#v}" >> $GITHUB_OUTPUT
              echo "skip=false" >> $GITHUB_OUTPUT
            fi
          else
            # Dev branch: snapshot version
            echo "version=dev-${{ gitea.sha }}" >> $GITHUB_OUTPUT
            echo "skip=true" >> $GITHUB_OUTPUT
          fi

      - name: Login to Gitea Container Registry
        run: |
          echo "${{ secrets.REGISTRY_TOKEN }}" | docker login git.avatic.de -u "${{ gitea.actor }}" --password-stdin

      - name: Prepare Docker tags
        id: tags
        run: |
          IMAGE_BASE="git.avatic.de/lcc_public/lcc"
          VERSION="${{ steps.version.outputs.version }}"
          TAGS="-t ${IMAGE_BASE}:${VERSION}"
          TAGS="${TAGS} -t ${IMAGE_BASE}:${{ gitea.sha }}"
          
          if [ "${{ gitea.ref_name }}" = "main" ]; then
            TAGS="${TAGS} -t ${IMAGE_BASE}:latest"
            TAGS="${TAGS} -t ${IMAGE_BASE}:main"
          elif [ "${{ gitea.ref_name }}" = "dev" ]; then
            TAGS="${TAGS} -t ${IMAGE_BASE}:dev"
          fi
          
          echo "tags=${TAGS}" >> $GITHUB_OUTPUT
          echo "image_base=${IMAGE_BASE}" >> $GITHUB_OUTPUT

      - name: Build Docker image
        run: |
          docker build \
            --build-arg BUILDKIT_INLINE_CACHE=1 \
            --build-arg APP_VERSION=${{ steps.version.outputs.version }} \
            ${{ steps.tags.outputs.tags }} \
            .

      - name: Push Docker images
        run: |
          IMAGE_BASE="${{ steps.tags.outputs.image_base }}"
          VERSION="${{ steps.version.outputs.version }}"
          
          echo "DEBUG: ref_name = ${{ gitea.ref_name }}"
          echo "DEBUG: event_name = ${{ gitea.event_name }}"
          echo "DEBUG: base_ref = ${{ gitea.base_ref }}"
          
          docker push ${IMAGE_BASE}:${VERSION}
          docker push ${IMAGE_BASE}:${{ gitea.sha }}
          
          if [ "${{ gitea.ref_name }}" = "main" ]; then
            echo "Pushing latest and main tags..."
            docker push ${IMAGE_BASE}:latest
            docker push ${IMAGE_BASE}:main
          elif [ "${{ gitea.ref_name }}" = "dev" ]; then
            echo "Pushing dev tag..."
            docker push ${IMAGE_BASE}:dev
          fi

      - name: Create and push git tag
        if: gitea.ref_name == 'main' && steps.version.outputs.skip != 'true' && steps.version.outputs.new_tag != ''
        run: |
          git config user.name "Gitea Actions"
          git config user.email "actions@gitea.local"
          git tag -a ${{ steps.version.outputs.new_tag }} -m "Release ${{ steps.version.outputs.new_tag }}"
          git push origin ${{ steps.version.outputs.new_tag }}

      - name: Deploy to Docker
        if: gitea.event_name == 'push' && (gitea.ref_name == 'main' || gitea.ref_name == 'dev')
        run: |
          mkdir -p ~/.ssh
          echo "${{ secrets.DEPLOY_KEY }}" > ~/.ssh/deploy_key
          chmod 600 ~/.ssh/deploy_key
          ssh-keyscan -H ${{ secrets.DEPLOY_HOST }} >> ~/.ssh/known_hosts
          
          BRANCH="${{ gitea.ref_name }}"
          DEPLOY_PATH="${{ secrets.DEPLOY_PATH }}"
          
          ssh -i ~/.ssh/deploy_key ${{ secrets.DEPLOY_USER }}@${{ secrets.DEPLOY_HOST }} << EOF
          cd ${DEPLOY_PATH}
          docker compose pull lcc-app-${BRANCH}
          docker compose --profile ${BRANCH} up -d lcc-app-${BRANCH}
          EOF