pipeline {
    agent any
    tools {
        jdk 'jdk21'
    }
    environment {
        BRANCH = 'develop'
        GIT_REPO = 'https://kamco.gitea.gs.dabeeo.com/dabeeo/kamco-dabeeo-training-api.git'
        DEPLOY_SERVER = '192.168.2.109'
        DEPLOY_USER = 'space'
        DEPLOY_PATH = '/home/space//kamco-training-api'
        SSH_CREDENTIALS_ID = 'jenkins-251215'
    }


    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('Transfer Project Files') {
          steps {
            script {
              echo "Transferring project files to ${env.DEPLOY_SERVER}..."

              sshagent(credentials: ["${env.SSH_CREDENTIALS_ID}"]) {
                sh """
                  # Create deployment directory structure on remote server
                  ssh -o StrictHostKeyChecking=no ${env.DEPLOY_USER}@${env.DEPLOY_SERVER} \
                    "mkdir -p ${env.DEPLOY_PATH}/build/libs"

                  # Transfer build artifacts with directory structure
                  scp -o StrictHostKeyChecking=no \
                    build/libs/ROOT.jar \
                    ${env.DEPLOY_USER}@${env.DEPLOY_SERVER}:${env.DEPLOY_PATH}/build/libs/

                  # Transfer Docker files
                  scp -o StrictHostKeyChecking=no \
                    Dockerfile-dev \
                    ${env.DEPLOY_USER}@${env.DEPLOY_SERVER}:${env.DEPLOY_PATH}/

                  scp -o StrictHostKeyChecking=no \
                    docker-compose-dev.yml \
                    ${env.DEPLOY_USER}@${env.DEPLOY_SERVER}:${env.DEPLOY_PATH}/

                  echo "✅ Project files transferred successfully"
                """
              }
            }
          }
        }

        stage('Docker Compose Deploy') {
          steps {
            script {
              echo "Deploying with Docker Compose on ${env.DEPLOY_SERVER}..."

              sshagent(credentials: ["${env.SSH_CREDENTIALS_ID}"]) {
                sh """
                  ssh -o StrictHostKeyChecking=no ${env.DEPLOY_USER}@${env.DEPLOY_SERVER} << 'EOF'
                    cd ${env.DEPLOY_PATH}

                    # Set IMAGE_TAG environment variable
                    export IMAGE_TAG=${env.COMMIT_HASH}

                    # Stop and remove existing containers
                    echo "Stopping existing containers..."
                    docker compose -f docker-compose-dev.yml down || true

                    # Build new Docker image
                    echo "Building Docker image with tag: \${IMAGE_TAG}..."
                    docker compose -f docker-compose-dev.yml build

                    # Tag as latest
                    docker tag kamco-cd-training-api:\${IMAGE_TAG} kamco-cd-training-api:latest

                    # Start containers
                    echo "Starting containers..."
                    docker compose -f docker-compose-dev.yml up -d

                    # Wait for application to be ready
                    echo "Waiting for application to be ready..."
                    for i in {1..30}; do
                      if curl -f http://localhost:7200/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"
                    docker compose -f docker-compose-dev.yml ps
                    docker compose -f docker-compose-dev.yml logs --tail=50
                    exit 1
EOF
                """
              }
            }
          }
        }

        stage('Cleanup Old Images') {
          steps {
            script {
              echo "Cleaning up old Docker images..."

              sshagent(credentials: ["${env.SSH_CREDENTIALS_ID}"]) {
                sh """
                  ssh -o StrictHostKeyChecking=no ${env.DEPLOY_USER}@${env.DEPLOY_SERVER} \
                    "docker images kamco-cd-training-api --format '{{.ID}} {{.Tag}}' | \
                     grep -v latest | tail -n +6 | awk '{print \\\$1}' | xargs -r docker rmi || true"

                  echo "✅ Cleanup completed"
                """
              }
            }
          }
        }
    }
}
