pipeline {
    agent any
    tools {
        jdk 'jdk21'
    }
    environment {
        BRANCH = 'develop'
        GIT_REPO = 'https://10.100.0.10:3210/dabeeo/kamco-dabeeo-backoffice.git'
    }


    stages {
        stage('Checkout') {
          steps {
            checkout([
              $class: 'GitSCM',
              branches: [[name: "${env.BRANCH}"]],
              userRemoteConfigs: [[
                url: "${env.GIT_REPO}",
                credentialsId: 'jenkins-dev-token'
              ]]
            ])
          }
        }
        stage('Get Commit Hash') {
          steps {
            script {
              env.COMMIT_HASH = sh(script: "git rev-parse --short HEAD", returnStdout: true).trim()
              echo "Current commit hash: ${env.COMMIT_HASH}"
            }
          }
        }

        stage('Build') {
          steps {
            sh "./gradlew clean build -x test"
          }
        }

        stage('Docker Build & Deploy') {
          steps {
            script {
              echo "Building Docker image with tag: ${env.COMMIT_HASH}"

              // IMAGE_TAG 환경변수 설정 후 docker-compose로 빌드 및 배포
              sh """
                export IMAGE_TAG=${env.COMMIT_HASH}

                # 기존 컨테이너 중지 및 제거
                docker-compose -f docker-compose-dev.yml down || true

                # 새 이미지 빌드
                docker-compose -f docker-compose-dev.yml build

                # latest 태그도 추가
                docker tag kamco-changedetection-api:${env.COMMIT_HASH} kamco-changedetection-api:latest

                # 컨테이너 시작
                docker-compose -f docker-compose-dev.yml up -d
              """

              // 헬스체크 대기
              echo "Waiting for application to be ready..."
              sh """
                for i in {1..30}; do
                  if docker exec kamco-changedetection-api curl -f http://localhost:8080/monitor/health > /dev/null 2>&1; then
                    echo "✅ Application is healthy!"
                    docker-compose -f docker-compose-dev.yml ps
                    exit 0
                  fi
                  echo "⏳ Waiting for application... (\$i/30)"
                  sleep 2
                done
                echo "⚠️ Warning: Health check timeout, checking container status..."
                docker-compose -f docker-compose-dev.yml ps
              """
            }
          }
        }

        stage('Cleanup Old Images') {
          steps {
            script {
              echo "Cleaning up old Docker images..."
              sh """
                # Keep latest 5 images, remove older ones
                docker images kamco-changedetection-api --format "{{.ID}} {{.Tag}}" | \
                  grep -v latest | tail -n +6 | awk '{print \$1}' | xargs -r docker rmi || true
              """
            }
          }
        }
    }
}
