name: Build and Deploy
on:
  push:
    branches: [main]
  pull_request:
    branches: [main]

jobs:
  build:
    runs-on: ubuntu-latest
    outputs:
      image-tags: ${{ steps.meta.outputs.tags }}
    steps:
      - name: Checkout code
        uses: actions/checkout@v4

      - name: Generate image metadata
        id: meta
        run: |
          REGISTRY="${{ vars.PACKAGES_REGISTRY }}"
          REPO="${{ gitea.repository }}"
          
          # Genera tag con timestamp e commit SHA
          TIMESTAMP=$(date -u +'%Y%m%d-%H%M%S')
          SHORT_SHA=$(git rev-parse --short HEAD)
          TAG="${REGISTRY}/${REPO}:${TIMESTAMP}-${SHORT_SHA}"
          LATEST_TAG="${REGISTRY}/${REPO}:latest"
          
          echo "tags=${TAG} ${LATEST_TAG}" >> $GITHUB_OUTPUT
          echo "tag=${TAG}" >> $GITHUB_OUTPUT
          echo "latest_tag=${LATEST_TAG}" >> $GITHUB_OUTPUT

      - name: Debug Docker setup
        run: |
          echo "=== Docker Environment ==="
          echo "DOCKER_HOST: ${DOCKER_HOST}"
          echo "DOCKER_TLS_VERIFY: ${DOCKER_TLS_VERIFY}"
          echo "DOCKER_CERT_PATH: ${DOCKER_CERT_PATH}"
          echo ""
          echo "=== Docker CLI Check ==="
          docker version
          docker ps

      - name: Build Docker image
        run: |
          echo "Building image: ${{ steps.meta.outputs.tag }}"
          docker build \
            -t "${{ steps.meta.outputs.tag }}" \
            -t "${{ steps.meta.outputs.latest_tag }}" \
            --label "git.commit=${{ gitea.sha }}" \
            --label "git.ref=${{ gitea.ref }}" \
            .

      - name: Log in to Gitea Container Registry
        if: github.event_name == 'push'
        run: |
          echo "${{ secrets.TOKEN }}" | docker login \
            -u "${{ secrets.USERNAME }}" \
            --password-stdin \
            "${{ vars.PACKAGES_REGISTRY }}"

      - name: Push Docker image
        if: github.event_name == 'push'
        run: |
          echo "Pushing images..."
          docker push "${{ steps.meta.outputs.tag }}"
          docker push "${{ steps.meta.outputs.latest_tag }}"
          echo "Push completed successfully"

      - name: Logout from Gitea Container Registry
        if: always()
        run: docker logout "${{ vars.PACKAGES_REGISTRY }}" || true

  deploy:
    name: Deploy to target
    needs: build
    runs-on: ubuntu-latest
    if: github.event_name == 'push'
    steps:
      - name: Call deploy endpoint
        run: |
          # Verifica che le variabili/secret siano impostati
          if [ -z "${{ vars.DEPLOY_URL }}" ] || [ -z "${{ secrets.DEPLOY_USERNAME }}" ] || [ -z "${{ secrets.DEPLOY_PASSWORD }}" ]; then
            echo "DEPLOY_URL, DEPLOY_USERNAME or DEPLOY_PASSWORD not set; skipping deploy step."
            exit 0
          fi
          echo "Triggering deploy endpoint..."
          # curl --fail ritorna exit code != 0 se lo status HTTP non è 2xx
          curl --fail -s -X POST \
            --user "${{ secrets.DEPLOY_USERNAME }}:${{ secrets.DEPLOY_PASSWORD }}" \
            "${{ vars.DEPLOY_URL }}"